我已经阅读了这个问题的许多解决方案,例如正在尝试使用数组到树
鉴于此数据:
[
{
"_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
}
]
并使用此代码
var arrayToTree = require('array-to-tree');
var tree = arrayToTree(data, {
parentProperty: 'parent',
customID: '_id'
});
我不明白为什么它会让我的 child 成为孤儿?即我正在拿回这个
[ { _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
的类型为 Number
,array-to-tree
似乎不知道该怎么办;
更改此项会将平面数组转换为树结构。
您可以循环遍历数组,将 keys _id
/parent
转换为 string
(如果它们数字
;
只有在您要求时我才会编辑此内容(但上述解决了问题)
关于Javascript:将普通 Node 数组(带有指向父 Node 的指针)转换为嵌套数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43181688/