javascript - 从数组中创建树并将父字段的表示更改为对象而不是 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": []
谢谢你的帮助!
解决方案
您可以采用单循环方法,并为每个找到的节点提供参考。
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; }
推荐阅读
- reactjs - 在 react-native 中用 createStructuredSelector 替换 useSelector
- java - Eclipse:使用 Coverage 进行测试会抛出 java.lang.instrument.IllegalClassFormatException
- ios - Swift右栏按钮项目填充问题?
- karate - 是否可以使用命令行覆盖在 Runner.path() 中声明的类路径?
- android - 如何触发深度链接?
- python - pygame游戏中的高分
- java - 为什么我在 findViewbyID 上收到错误消息?
- r - 是否可以在 ggplot2 的单个时间序列图中绘制多条趋势线?
- java - java android retrofit2 - 如何访问 JSON 响应对象
- javascript - 矢量之间的碰撞检查 - 移动矢量 - HTML、JS、P5