ua_boaz ua_boaz - 4 months ago 14
JSON Question

traverse a json tree structure and add all nodes into a list

So i have a json object that i would like to traverse and add all the nodes in a linear list.below is my 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" : [] }
];


and i want to create a list of all objects present in the tree, objects need to be like this:
{ "name" : "Joe", "age" : "21"}

Answer

Using a recursive function is an easy to traverse and flatten your array. Here's a sample algorithim:

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));