javascript修复树数组

时间:2019-03-01 03:40:57

标签: javascript arrays node.js json

你好,我有json数组

它的家谱

[
  {
    "_id": "5c789fd2952b2353b4eba417",
    "level": 1,
    "children": [
      {
        "_id": "5c78a09a0dd5f05134b7a7ce",
        "level": 2,
        "children": [
          {
            "_id": "5c78a0a70dd5f05134b7a7d3",
            "level": 3,
            "children": []
          }]}]
  },
  {
    "_id": "5c78a08a0dd5f05134b7a7c9",
    "level": 1,
    "children": []
  }
]

我想将其转换为这样

[
  {
    "_id": "5c789fd2952b2353b4eba417",
    "level": 1
  },
  {
    "_id": "5c78a09a0dd5f05134b7a7ce",
    "level": 2
  },
  {
    "_id": "5c78a0a70dd5f05134b7a7d3",
    "level": 3
  },
  {
    "_id": "5c78a08a0dd5f05134b7a7c9",
    "level": 1
  }
]

任何好的修复功能?????

我尝试了很多方法,但是如果有更多的孩子,我需要添加很多代码:(

3 个答案:

答案 0 :(得分:1)

您可以使用Array.prototype.reduce()Array.prototype.push()Spread syntax

来构建递归函数。

代码:

const data = [{"_id": "5c789fd2952b2353b4eba417","level": 1,"children": [{"_id": "5c78a09a0dd5f05134b7a7ce","level": 2,"children": [{"_id": "5c78a0a70dd5f05134b7a7d3","level": 3,"children": []}]}]},{"_id": "5c78a08a0dd5f05134b7a7c9","level": 1,"children": []}];
const getResult = array => array.reduce((a, c) => {
  a.push({ _id: c._id, level: c.level });
  return c.children.length ? [...a, ...getResult(c.children)] : a;
}, []);

console.log(getResult(data));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

您可以使用以下软件包:[Github] https://www.npmjs.com/package/treeify-js

[NPM] Coordinated Controls

安装:

$ npm install --save-dev treeify-js

treeify软件包具有 untreeify API,该API用于将树对象转换为平面数组。

答案 2 :(得分:-2)

我使用splitjoin来解决它。

split(',"children":[]').join("").split(',"children":[').join("},").split("}").join("").split("]").join("").split("{").join("").split("[").join("").split(',"_id').join('},{"_id');