简体   繁体   English

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

[英]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 ; 似乎如果_idNumber类型,则array-to-tree不知道该怎么做;

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 ; 您可以遍历数组将 _id / parent转换为string如果它们是number

I'll only edit this if you ask for it (but the above solves) 如果您需要,我只会对其进行编辑(但以上方法可以解决)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将包含嵌套对象、字符串、数组的节点转换为无序列表(Javascript) - Convert nodes that consists of nested objects, strings, array into an unordered list (Javascript) 在像数据结构这样的嵌套树中,如何通过父节点的 id 将子节点添加到父节点的子数组中? - How does one, in a nested tree like data-structure, add child-nodes to a parent-node's children-array by a parent-node's id? 如何将具有存储为键值对象的节点的树转换为具有存储为 Javascript 中的对象数组的节点的树结构? - How to convert tree having nodes stored as key-value objects to a tree structure having nodes stored as array of objects in Javascript? 使用普通JavaScript遍历文本节点 - Traverse text nodes with plain javascript 用于展平嵌套数组并跟踪所有父节点的递归函数(Javascript) - Recursive function to flatten nested array and keeping track of all parent nodes (Javascript) 如何将普通数组转换为嵌套在父对象中的嵌套对象 - how to convert plain array into nested object which is nested into parent object 使用不同的键将嵌套的 JSON 转换为 JavaScript 中的节点和链接结构 - Converting Nested JSON to nodes and links structure in JavaScript with different keys 如何将具有父子关系的嵌套数组转换为普通数组? - How to convert a nested array with parent child relationship to a plain array? 将最大值传播到嵌套树javascript中的父节点 - Propagate max value to parent nodes in nested tree javascript 递归一维嵌套数组以更新父节点 - Recursing a 1D nested array to update parent nodes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM