1

将树结构的数组平铺成一个普通的数组应该怎么解决?

相关代码

cost treeNode = [{
    parentId: 0,
    title: "目录1",
    id:1,
    children: [{
       parentId: 1,
       title: "子目录1-1",
       id:22, 
    },{
       parentId: 1,
       title: "子目录1-2",
       id:33, 
    }],
},{
    parentId: 0,
    title: "目录2",
    id:2,
    children: [{
       parentId: 2,
       title: "子目录2-1",
       id:44, 
    },{
       parentId: 1,
       title: "子目录2-2",
       id:55, 
    }],
}];

变成这种结构

const arr = [{
 id:1,
 parentId:0,
 title: "目录1"
},{
 id:22,
 parentId:1,
 title: "子目录1-1"
},{
 id:33,
 parentId:1,
 title: "子目录1-2"
},{
 id:2,
 parentId:0,
 title: "目录2"
},{
 id:44,
 parentId:1,
 title: "子目录2-1"
},{
 id:55,
 parentId:2,
 title: "子目录2-2"
}];

你期待的结果是什么?实际看到的错误信息又是什么?

hehehe 253
2018-12-20 提问
3 个回答
1

已采纳
var result = []
function flat(nodes, parentId) {
  if(!nodes || nodes.length === 0) return []
  nodes.forEach(node => {
    result.push({title: node.title, id: node.id, parentId: parentId})
    return flat(node.children, node.id)
  })
}

flat(treeNode, 0)
1

递归遍历就好

function trans(data) {
    let transData = []

    function go(data) {
        for (let item of data) {
            let {
                parentId, title, id, children
            } = item;
            let newItem = {
                parentId, title, id
            }
            transData.push(newItem)
            if (children) {
                go(children)
            }
        }
    }
    go(data)
    return transData;
}
let newData = trans(treeNode)
console.log(newData)
1

5743已经答得很完善了,做一点修改吧,既然已经存在parentID,那么就不需要通过递归的方式给ID了,只需要取即可。

const opentree = tree => {
      let result = [];
      const flat = nodes => {
        if (nodes && nodes.length > 0)
          nodes.forEach(node => {
            result.push({ title: node.title, id: node.id, parentId: node.parentId });
            flat(node.children);
          });
      };
      flat(tree);
      return result;
    };

撰写答案

推广链接