遍历json树结构并将所有节点添加到列表中

时间:2016-07-28 03:30:29

标签: javascript arrays json recursion tree

所以我有一个json对象,我想遍历并添加线性列表中的所有节点。贝洛是我的json

    [{ "name" : "Joe", "age" : "21", "children" : [
        { "name" : "Smith", "age" : "42", "children" : [] },
        { "name" : "Gary", "age" : "21", "children" : [
            { "name" : "Jenifer", "age" : "23", "children" : [
                { "name" : "Dani", "age" : "32", "children" : [] },
                { "name" : "Max", "age" : "34", "children" : [] }
            ]}
        ]}
    ]},
    { "name" : "Albert", "age" : "33", "children" : [] },
    { "name" : "Ron", "age" : "29", "children" : [] }
];

我希望创建树中所有对象的列表,对象必须如下:
{ "name" : "Joe", "age" : "21"}

4 个答案:

答案 0 :(得分:2)

使用递归函数很容易遍历并展平您的数组。这是一个示例算法:

function flatten(items, result = []) {
  if (items.length) {
    var item = items.shift();
    result.push({
      name: item.name,
      age: item.age
    });

    if (item.children && item.children.length) {
      result = flatten(item.children, result);
    }

    return flatten(items, result);
  } else {
    return result;
  }
}

var people = [{
  "name": "Joe",
  "age": "21",
  "children": [{
    "name": "Smith",
    "age": "42",
    "children": []
  }, {
    "name": "Gary",
    "age": "21",
    "children": [{
      "name": "Jenifer",
      "age": "23",
      "children": [{
        "name": "Dani",
        "age": "32",
        "children": []
      }, {
        "name": "Max",
        "age": "34",
        "children": []
      }]
    }]
  }]
}, {
  "name": "Albert",
  "age": "33",
  "children": []
}, {
  "name": "Ron",
  "age": "29",
  "children": []
}];

console.log(flatten(people));

答案 1 :(得分:1)

解决此问题的最简单方法是使用transverse函数recursive树结构。

在我的解决方案中,我使用instanceOf API检查横向所处的元素类型,然后确定要采取的操作。

查看:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/instanceof

示例:

let result = [];
let people =
    [
      { "name" : "Joe", "age" : "21", "children" : [
        { "name" : "Smith", "age" : "42", "children" : [] },
        { "name" : "Gary", "age" : "21", "children" : [
          { "name" : "Jenifer", "age" : "23", "children" : [
            { "name" : "Dani", "age" : "32", "children" : [] },
            { "name" : "Max", "age" : "34", "children" : [] }
          ]}
        ]}
      ]},
      { "name" : "Albert", "age" : "33", "children" : [] },
      { "name" : "Ron", "age" : "29", "children" : [] }
    ];

function transverse(element, result) {
    if (element instanceof Array)
      element.forEach(item => { transverse(item, result); });
    else if (element instanceof Object) {
      result.push({ name: element.name, age: element.age });
      if (element.hasOwnProperty("children")) {
        transverse(element.children, result);
      }
    }
}

transverse(people, result);
console.log(result);

<强>输出:

[ { name: 'Joe', age: '21' },
  { name: 'Smith', age: '42' },
  { name: 'Gary', age: '21' },
  { name: 'Jenifer', age: '23' },
  { name: 'Dani', age: '32' },
  { name: 'Max', age: '34' },
  { name: 'Albert', age: '33' },
  { name: 'Ron', age: '29' } ]

答案 2 :(得分:0)

假设这是一个没有排序的简单遍历,可以通过两个简单的函数来完成:

mapView.settings.compassButton = YES;

mapView.settings.myLocationButton = YES;

mapView.addObserver(self, forKeyPath: "myLocation", options: .New, context: nil)

dispatch_async(dispatch_get_main_queue(), ^{
    mapView.myLocationEnabled = YES;
  });

答案 3 :(得分:0)

由于已将其恢复,因此我们可能希望访问一个更简单的ES6解决方案:

const extract = (people = []) => 
  people .flatMap (({children = [], ... rest}) => [rest, ... extract (children)])

const people = [{name: "Joe", age: "21", children: [{name: "Smith", age: "42", children: []}, {name: "Gary", age: "21", children: [{name: "Jenifer", age: "23", children: [{name: "Dani", age: "32", children: []}, {name: "Max", age: "34", children: []}]}]}]}, {name: "Albert", age: "33", children: []}, {name: "Ron", age: "29", children: []}]

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

我们实现了一个非常简单的(预排序)深度优先遍历层次结构,返回除每个节点的"children"属性以外的所有内容。