且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从自引用数组转换为树中的嵌套数组

更新时间:2022-11-22 18:05:26

这将完成这项工作:

function nest (array) {
  nested = [];
  for (var i = 0; i < array.length; i++) {
    var parent = array[i].parent;
    if (!parent) {
      nested.push(array[i]);
    } else {
      // You'll want to replace this with a more efficient search
      for (var j = 0; j < array.length; j++) {
        if (array[j].id === parent) {
          array[j].children = array[j].children || [];
          array[j].children.push(array[i]);
        }
      }
    }
  }
  return nested;
}

的第二个循环是寻找父母的低效方式;如果您要嵌套多个项目,则需要将其替换为不扫描整个数组的内容。

The second for loop is an inefficient way of finding the parent; if you ever have more than a few items to nest, you'll want to replace it with something that doesn't scan the entire array.