Storing nodes at each level of depth in json object in seperate array

Viewed 671

i have a json, something like this

{
   "a": {
      "b1": "blah blah",
      "b2": "ahsbefbasef",
      "b3": "adsfad af"
   },
   "c": {
      "d1":"asef",
      "d2":"fefef",
      "d3":"ffgfgf"
   }
}

now i want to traverse through this json and get all the nodes-depth wise, as in i want to store nodes with 0 depth(a, c) in one array, nodes with depth 1 (c1,c2,c3,d1,d2,d3) in another array, and so on and so forth, basically breaking json object and storing nodes present at each depth in seperate array

2 Answers

You could take an recursive approach by using an incremented level for each nested object. Then take the level for the result and for adding the keys of same level.

function iter(object, level) {
    var keys = Object.keys(object);

    level = level || 0;
    result[level] = result[level] || [];
    Array.prototype.push.apply(result[level], keys);

    keys.forEach(function (key) {
        if (object[key] && typeof object[key] === 'object') {
            iter(object[key], level + 1);
        }
    });
}

var object = { a: { b1: "blah blah", b2: "ahsbefbasef", b3: "adsfad af" }, c: { d1: "asef", d2: "fefef", d3: "ffgfgf" } },
    result = [];

iter(object);

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

You can use below code to achieve your requirements. and in ECMAScript2015 (a.k.a. ES6), you can use the spread operator to append multiple items at once:

I have benchmarked my code here , you can check below code is faster than accepted answer.

var obj = {
  "a": {
    "b1": "blah blah",
    "b2": "ahsbefbasef",
    "b3": "adsfad af"
  },
  "c": {
    "d1": "asef",
    "d2": "fefef",
    "d3": "ffgfgf"
  }
}

var response = {};
recursive(obj, 0, response);
console.log("result:",response);


function recursive(passedObject, depth, response) {
    var keys = Object.keys(passedObject);
    response[depth] = response[depth] || [];
    response[depth].push(...keys);

    keys.forEach(function(key){
    if (passedObject[key] && typeof passedObject[key] === 'object') {
        recursive(passedObject[key], depth + 1, response)
    }
 })
}

Output:

result: 
{
 0 : ["a", "c"]
 1 : ["b1", "b2", "b3", "d1", "d2", "d3"]
}

Benchmarking results here:

enter image description here

Related