javascript - Convert An Relational Array to Tree Object in Typescript
问题描述
I have structure database in array of objects stored like this;
array = [ {"name": "a", "id": "1", "parentId": NULL},
{"name": "b", "id": "2", "parentId": "1"},
{"name": "c", "id": "3", "parentId": "1"},
{"name": "d", "id": "4", "parentId": "1"},
{"name": "e", "id": "5", "parentId": "2"},
{"name": "f", "id": "6", "parentId": "3"},
{"name": "g", "id": "7", "parentId": "3"},
{"name": "h", "id": "8", "parentId": "4"},
{"name": "j", "id": "9", "parentId": "4"}]
And I want to get like this tree object;
{
a: {
b: {
e: {}
},
c: {
f: {},
g: {}
},
d: {
h: {},
j: {}
}
}
}
解决方案
你可以使用递归:
buildTree(arr, root) {
return {
[root.name]: arr
.filter(x => x.parentId === root.id)
.map(x => buildTree(x))
.reduce((a, b) => ({ ...a, ...b }), {}),
};
}
const tree = buildTree(array, array.find(x => !x.parentId));
推荐阅读
- python - 如何减少 GPU 推理时间并提高其利用率?
- swing - Jframe Jpanel - 打开窗口时显示结果
- c# - 'Form1.myAxMap' 由于其保护级别而无法访问
- c# - 设置 cookie 选项
- java - jxbrowser 7 JSObject.toJSONString() 的替代方法
- python - IndexError:索引 2 超出 Sklearn LabelEncoder 中大小为 2 的轴 1 的范围
- reactjs - 无法在reactjs中选中和取消选中复选框
- java - WebLogic 版本 12.2.1.1 及更高版本上的“ClassNotFoundException:org.objectweb.asm.ClassVisitor”(文档 ID 2526226.1)
- microsoft-graph-api - 获取与 MS Graph API 中的事件关联的 EventMessage
- selenium - 拒绝加载脚本,因为它违反了以下内容安全策略指令:script-src error with ChromeDriver Chrome and Selenium