zoukankan      html  css  js  c++  java
  • JS 树结构数据解构成平面数据 Tree to Array<primary>

    将tree数据解构成普通的数值数据结构

    1、基础实现

    // 树形解构转平铺
    // data 集合数据;list 返回集合
    function treeToTile(data, list){
        if (tools.isArray(data)) {
            return;
        }
        data.forEach(item => {
          if (item.children && item.children.length) {
            treeToTile(item.children, list)
          } else {
            list.push(item)
          }
        });
        return list;
    }
    

    2、结构成 指定对象 的普通数据集合

    // 树形解构转平铺
    // data 集合数据;list 返回集合; primaryObj 原集合对象; resultObj 返回新的集合对象
    // 例 primaryObj = ['name', 'age']; resultObj = ['title', 'years']; 返回的集合中将name和age属性值赋值给了title和years属性!
    function treeToTileGivenObject(data, list, primaryObj, resultObj){
        data.forEach(item => {
          if (primaryObj.length && resultObj.length) {
            let obj = {};
            primaryObj.map((m,i) => {
              obj[resultObj[i]] = item[m];
            });
          }
          
          if (item.children && item.children.length) {
            treeToTileGivenObject(item.children, list,primaryObj, resultObj)
          } else {
            (primaryObj.length && resultObj.length) ? list.push(obj) : list.push(item);
          }
        });
        return list;
      }
    

    3、工具类方法tools

    isArray(arr) {
            return Object.prototype.toString.call(arr) === '[object Array]' ? true : false;
    }
    

    4、调用

    1、 treeToTile(dataList, []);
    2、treeToTileGivenObject(dataList, [], [], []); 
    3、treeToTileGivenObject(dataList, [], ['name', 'age'], ['title', 'years']); 
    

    5、数据结构范例

    let tree = [
      {
        name: 'jack',
        age: '20',
        children: []
      },
      {
        name: 'aa',
        age: '20',
        children: [
          {
            name: 'aa-1',
            age: '20',
            children: [
              {
                name: 'aa11-1',
                age: '20',
                children: []
              }
            ]
          },
          {
            name: 'aa-1',
            age: '20',
            children: []
          },
          {
            name: 'aa-1',
            age: '20',
            children: []
          }
        ]
      }
    ];
    
    返回:
    let arr = [
    {
        name: 'jack',
        age: '20',
        children: []
    },
    {
        name: 'aa',
        age: '20',
        children: []
    },
    {
        name: 'aa-1',
        age: '20',
        children: []
    }
    ……
    ];
    
    
  • 相关阅读:
    手动渗透测试漏洞
    博弈论一 [ 巴什游戏 ]
    [Error]EOL while scanning string literal
    Swift
    Swift
    Swift
    Swift
    Swift
    Swift
    Swift
  • 原文地址:https://www.cnblogs.com/min77/p/15235281.html
Copyright © 2011-2022 走看看