[英]Javascript: Convert a plain array of nodes (with pointers to parent nodes) to a nested data structure
I have read many of the solutions to this problem and for example am trying with array-to-tree 我已经阅读了许多解决此问题的方法,例如正在尝试使用数组到树
Given this data: 给定此数据:
[
{
"_id": 33,
"parent": null,
"name": "Wealth and Investment Management and Insurance",
"code": "wm-0001",
"__v": 0
},
{
"_id": 34,
"parent": null,
"name": "Corporate and Investment Banking",
"code": "cib-0001",
"__v": 0
},
{
"_id": 35,
"parent": 33,
"name": "WIMI Business Unit 1",
"code": "WIMBU-0001",
"__v": 0
}
]
And using this code 并使用此代码
var arrayToTree = require('array-to-tree');
var tree = arrayToTree(data, {
parentProperty: 'parent',
customID: '_id'
});
I cannot understand why its orphaning my children? 我不明白为什么孤儿会成为孤儿? ie I am getting this back 即我回来了
[ { _id: 33,
parent: null,
name: 'Wealth and Investment Management and Insurance',
code: 'wm-0001',
__v: 0 },
{ _id: 34,
parent: null,
name: 'Corporate and Investment Banking',
code: 'cib-0001',
__v: 0 } ]
It seems that array-to-tree
doesn't know what to do if _id
is of type Number
; 似乎如果_id
为Number
类型,则array-to-tree
不知道该怎么做;
Changing this converts the flat array to a tree structure. 更改此选项会将平面数组转换为树结构。
You can loop through the array to convert the keys _id
/ parent
to string
if they are number
; 您可以遍历数组将键 _id
/ parent
转换为string
如果它们是number
;
I'll only edit this if you ask for it (but the above solves) 如果您需要,我只会对其进行编辑(但以上方法可以解决)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.