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

代码实现

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']

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

猜你喜欢

转载自blog.csdn.net/ddx2019/article/details/108224898