• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

js 递归实现树形结构父子数据拼接

武飞扬头像
茶荼
帮助2

递归实现多层结构的父子孙数据的拼接,将树形结构转化为[a-aa-aa]数据

  1.  
    let aa = [{
  2.  
    title:'A',
  3.  
    children:[{
  4.  
    title: 'AA',
  5.  
    children: [{
  6.  
    title: 'AAA1'
  7.  
    },{
  8.  
    title: 'AAA2'
  9.  
    },{
  10.  
    title: 'AAA3'
  11.  
    }]
  12.  
    },{
  13.  
    title: 'AA2',
  14.  
    children: [{
  15.  
    title: 'AAA2/1'
  16.  
    },{
  17.  
    title: 'AAA2/2'
  18.  
    },{
  19.  
    title: 'AAA2/3'
  20.  
    }]
  21.  
    }]
  22.  
    },{
  23.  
    title:'B',
  24.  
    children:[{
  25.  
    title: 'BB',
  26.  
    children: [{
  27.  
    title: 'BBB1'
  28.  
    },{
  29.  
    title: 'BBB2'
  30.  
    },{
  31.  
    title: 'BBB3'
  32.  
    }]
  33.  
    }]
  34.  
    },{
  35.  
    title:'C',
  36.  
    children:[{
  37.  
    title: 'CC',
  38.  
    }]
  39.  
    }]
  40.  
    let abc = this.findIndexArray(aa,[],[]);
学新通
  1.  
    // 递归属性结构转化为扁平结构
  2.  
    findIndexArray (data, indexArray, all) {
  3.  
    let arr = Array.from(indexArray);
  4.  
    for (let i = 0, len = data.length; i < len; i ) {
  5.  
    arr.push(data[i].title);
  6.  
    let children = data[i].children;
  7.  
    if (children && children.length) {
  8.  
    this.findIndexArray(children, arr, all);
  9.  
    } else {
  10.  
    let joinArr = arr.join("-");
  11.  
    if (!all.includes(joinArr)) {
  12.  
    all.push(joinArr);
  13.  
    }
  14.  
    }
  15.  
    arr.pop();
  16.  
    }
  17.  
    return all;
  18.  
    },
学新通

最终获得数据结构如下:

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhhkjhif
系列文章
更多 icon
同类精品
更多 icon
继续加载