通过嵌套的json子对象循环

问题描述 投票:0回答:2

具有此JSON有效负载,包含ID,名称和子代数组。在这里,我需要获取所有元素的ID,包括根和所有嵌套的子代。

{
  "_id": "-1",
  "_name": "root",
  "_children": [
    {
      "_id": "1",
      "_name": "Child 1",
      "_children": [
        {
          "_id": "1-1",
          "_name": "Child 1-1",
          "_children": [
            {
              "_id": "1-1-1",
              "_name": "Child 1-1-1",
              "_children": [

              ]
            }
          ]
        },
        {
          "_id": "1-2",
          "_name": "Child 1-2",
          "_children": [

          ]
        },
        {
          "_id": "1-3",
          "_name": "Child 1-3",
          "_children": [

          ]
        }
      ]
    },
    {
      "_id": "2",
      "_name": "Child 2",
      "_children": [
        {
          "_id": "2-2",
          "_name": "Child 2-2",
          "_children": [

          ]
        }
      ]
    }
  ]
}

如何循环遍历以获得所有子代+根的id值。

这是我尝试使用嵌套函数但无法正常工作的内容。

getNestedChildren(arr) {
  var out = []
    for(var i in arr[0].children) {
      out.push(arr[i].id);
        if(arr[i].children && arr[i].children.size() > 0) {
            var children = this.getNestedChildren(arr[i].children)
        }
    }
typescript angular5
2个回答
1
投票

您可以使用递归并通过引用修改“结果数组”。

例如,如果您的嵌套对象存储在变量data中,则:

function addNestedChildrenToArray(obj, resultArray) {
    resultArray.push(obj._id);
    obj._children.forEach(child => addNestedChildrenToArray(child, resultArray));
}

const resultArray = [];
addNestedChildrenToArray(data, resultArray);
// resultArray now contains the results
console.log(resultArray);

You can test it here: https://es6console.com/k6ehwu5p/


0
投票

您可以展平一棵树,然后简单地获取ID。请参见工作示例here

const tree = {
  "_id": "-1",
  "_name": "root",
  "_children": [
    // ...
  ]
}

function flattenTree(tree) {
  if (!tree) {
      return [];
  }

  if (tree._children) {
      const result = tree._children.reduce((prev, current) => prev.concat(flattenTree(current)), [tree]);
      return result;
  } else {
      return [tree];
  }
}

const plain = flattenTree(tree);
const ids = plain.map(value => value._id);
© www.soinside.com 2019 - 2024. All rights reserved.