Monday, 3 April 2017

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? 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 } ]



via user4447899

No comments:

Post a Comment