Reputation: 332
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? i.e. 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 } ]
Upvotes: 0
Views: 64
Reputation: 10414
It seems that array-to-tree
doesn't know what to do if _id
is of type Number
;
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
;
I'll only edit this if you ask for it (but the above solves)
Upvotes: 1