首页 > 解决方案 > 从数组中创建树并将父字段的表示更改为对象而不是 ID

问题描述

我堆积了一些琐碎的问题,但找不到解决方案。任何帮助将不胜感激。

我有一系列对象

[
    {
        id: 1,
        title: 'home',
        parent: null,
    },
    {
        id: 2,
        title: 'about',
        parent: null,
    },
    {
        id: 3,
        title: 'team',
        parent: 2,
    },
    {
        id: 4,
        title: 'company',
        parent: 2,
    },
    ,
    {
        id: 5,
        title: 'department',
        parent: 4,
    },
];

为了制作树,我使用了这个功能:Solution from here

const treeify = (arr) => {
    const tree = [];
    const lookup = {};
    arr.forEach((o) => {
        lookup[o.id] = o;
        lookup[o.id].children = [];
    });
    arr.forEach((o) => {
        if (o.parent !== null) {
            lookup[o.parent].children.push(o);
        } else {
            tree.push(o);
        }
    });
    return tree;
};

最后我有这样的树:

[
  {
    "id": 1,
    "title": "home",
    "parent": null,
    "children": []
  },
  {
    "id": 2,
    "title": "about",
    "parent": null,
    "children": [
      {
        "id": 3,
        "title": "team",
        "parent": 2,
        "children": []
      },
      {
        "id": 4,
        "title": "company",
        "parent": 2,
        "children": [
          {
            "id": 5,
            "title": "department",
            "parent": 4,
            "children": []
          }
        ]
      }
    ]
  }
]

问题是:如何用对象本身替换父 ID?

我想要这样的结果:

            "id": 4,
            "title": "company",
            "parent":  { // <-- how to change just id to object here
                        "id": 2,
                        "title": "about",
                        "parent": null,
                       },
            "children": []

谢谢你的帮助!

标签: javascript

解决方案


您可以采用单循环方法,并为每个找到的节点提供参考。

const
    data = [{ id: 1, title: 'home', parent: null, }, { id: 2, title: 'about', parent: null }, { id: 3, title: 'team', parent: 2 }, { id: 4, title: 'company', parent: 2 }, { id: 5, title: 'department', parent: 4 }],
    tree = function (data, root) {
        var t = {};
        data.forEach(o => {
            Object.assign(t[o.id] = t[o.id] || {}, o);
            t[o.parent] = t[o.parent] || {};
            t[o.parent].children = t[o.parent].children || [];
            t[o.parent].children.push(t[o.id]);
            if (t[o.id].parent !== null) t[o.id].parent = t[t[o.id].parent];
        });
        return t[root].children;
    }(data, null);

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


推荐阅读