Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 258
jayant mishra Avatar asked Nov 24 '25 22:11

jayant mishra


1 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; }
like image 197
Nina Scholz Avatar answered Nov 27 '25 12:11

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!