简体   繁体   中英

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 ;

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM