Skip to content Skip to sidebar Skip to footer

Javascript- Iterate Over Nested Objects, Getting Values And Chained Keys

Having the object : Nested1: { 'nested21': { 'nested31': { value: 'im sooo nested' } , 'nested32': { value: 'im sooo nested'

Solution 1:

Got it

var obj, traverse;

obj = {
  a: {
    b: 1,
    c: 2
  },
  d: {
    e: 3,
    f: 4
  }
};

traverse = function(node, path) {
  var pairs;
  if (!(pairs = _(node).pairs()).length) {
    return [
      {
        keys: path,
        value: node
      }
    ];
  } else {
    return [].concat.apply([], _(pairs).map(function(kv) {
      return traverse(kv[1], path.concat(kv[0]));
    }));
  }
};

console.log(traverse(obj, []));

Post a Comment for "Javascript- Iterate Over Nested Objects, Getting Values And Chained Keys"