用javascript写父母的孩子的有效方法

问题描述 投票:1回答:2

var array = [
  {id: 1, name: "Father", parent_id: null},
  {id: 2, name: "Child", parent_id: 1},
  {id: 3, name: "Child", parent_id: 1},
  {id: 4, name: "ChildChild", parent_id: 2},
  {id: 5, name: "ChildChildChild", parent_id: 4}
]

  for(var i in array){
    if(array[i].parent_id == null){
       console.log(array[i].name);
    } else {
      for(var j in array){
          if(array[i].parent_id == array[j].id && array[j].parent_id == null){
              console.log(">" + array[i].name);
              for(var x in array){
                  if(array[i].id == array[x].parent_id){
                      console.log(">>" + array[x].name);
                  }
              }
          }
      }
  }
}

输出:

Father
>Child
>>ChildChild
>Child

我有这个具有ID,名称和parent_id的数组。现在它是固定的,但它可以有多个数组,并且可以嵌套n次。

我在这里所做的是遍历每个数组,并试图找出哪些是父母,哪些是孩子。

我想知道是否有更有效的方法来编写此代码。例如,我添加了第五个id,但这需要另一个for循环,依此类推。输出将只是打印出的树一样。

javascript performance for-loop
2个回答
2
投票

您可以创建一棵树,然后进行输出。

const
    print = ({ name, children = [] }) => {
        console.log(name)
        children.forEach(print);
    },
    array = [{ id: 1, name: "Father", parent_id: null }, { id: 2, name: "Child", parent_id: 1 }, { id: 3, name: "Child", parent_id: 1 }, { id: 4, name: "ChildChild", parent_id: 2 }, { id: 5, name: "ChildChildChild", parent_id: 4 }],
    tree = function (data, root) {
        var t = {};
        data.forEach(o => {
            Object.assign(t[o.id] = t[o.id] || {}, o);
            t[o.parent_id] = t[o.parent_id] || {};
            t[o.parent_id].children = t[o.parent_id].children || [];
            t[o.parent_id].children.push(t[o.id]);
        });
        return t[root].children;
    }(array, null);

tree.forEach(print);
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }

2
投票

您可以使用Map通过ID来对节点进行键控,然后使用递归以深度优先顺序遍历它们:

var array = [{id: 1, name: "Father", parent_id: null},{id: 2, name: "Child", parent_id: 1},{id: 3, name: "Child", parent_id: 1},{id: 4, name: "ChildChild", parent_id: 2},{id: 5, name: "ChildChildChild", parent_id: 4}];

let map = new Map(array.map(({id}) => [id, []])).set(null, []);
array.forEach(node => map.get(node.parent_id).push(node));
function dfs(nodes, indent="") {
    for (let node of nodes) {
        console.log(indent + node.name);
        dfs(map.get(node.id), indent+">");
    }
}
dfs(map.get(null));
© www.soinside.com 2019 - 2024. All rights reserved.