首页 > 解决方案 > 从数组中查找父母和孩子

问题描述

在下面的数组中,一些项目是父项,其中一些是其子项。

我想找到父母(深度为0)和他们的孩子(嵌套深度为1-深度2-深度3),然后推送到另一个数组。

到目前为止,我所做的仅适用于深度 0 和深度 1,不知道如何处理更多深度。

这是小提琴:http: //jsfiddle.net/s3x5f4ap/2/

const comments = [
  { "depth": 0,"id": "f35vz2f"},
  { "depth": 0,"id": "f359354"},
  {   "depth": 1,"id": "f35e0b0", "parent_id": "f359354" },
  {     "depth": 2, "id": "f35ji24", "parent_id": "f35e0b0"},
  {     "depth": 2, "id": "f35rnwb", "parent_id": ""},
  {     "depth": 2, "id": "f35ojh4", "parent_id": "f35e0b0" },
  {       "depth": 3, "id": "f35lmch", "parent_id": "f35ji24"},
  {       "depth": 3, "id": "f35kl96", "parent_id": "f35ji24"}]

const parent = comments.filter(cm => cm.depth == 0);
final = [];
final = parent;

comments.forEach(a => {
  final.forEach(c => {
    if (c.id == a.parent_id) {
      c.child = []
      c.child.push(a);
    }
  })
})

console.log(final)

标签: javascriptarraysjson

解决方案


您可以收集节点的所有关系并构建一棵树。

var data = [{ depth: 0, id: "f35vz2f" }, { depth: 0, id: "f359354" }, { depth: 1, id: "f35e0b0", parent_id: "f359354" }, { depth: 2, id: "f35ji24", parent_id: "f35e0b0" }, { depth: 2, id: "f35rnwb", parent_id: "" }, { depth: 2, id: "f35ojh4", parent_id: "f35e0b0" }, { depth: 3, id: "f35lmch", parent_id: "f35ji24" }, { depth: 3, id: "f35kl96", parent_id: "f35ji24" }],
    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;
    }(data, undefined);

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


推荐阅读