Javascript:将一个普通的节点数组(带有指向父节点的指针)转换为嵌套的数据结构

时间:2017-04-03 10:01:30

标签: javascript node.js tree

我已经阅读了很多解决这个问题的方法,例如我正在尝试使用array-to-tree

鉴于此数据:

[
  {
    "_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'
        });

我无法理解为什么它的孤儿我的孩子?即我回来了

[ { _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 } ]

1 个答案:

答案 0 :(得分:1)

如果array-to-tree的类型为_idNumber似乎不知道该怎么办;

更改此项将平面数组转换为树形结构。

如果它们是_id,您可以遍历数组以将 parent / string转换为number;

如果你要求它,我只会编辑它(但上面的解决方案)