将树形结构数据转为平级数组 (树形菜单和扁平数组)

代码实现

function treeConvertToArr(tree) {
  let arrs = [];
  let result = [];
  arrs = arrs.concat(tree);
  while (arrs.length) {
    let first = arrs.shift(); // 弹出第一个元素
    if (first.children) {
      //如果有children
      arrs = arrs.concat(first.children);
      delete first["children"];
    }
    result.push(first);
  }
  return result;
}

let treeNode=[{label:"111",id:'111',children:[{label:'222',value:"222"}]}];
treeConvertToArr(treeNode) //  得到: [{label:"111",id:'111'},{label:"222",id:'222']

将平级数据转为树形结构的写法,见 博文


版权声明:本文为ddx2019原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。