RJ Mohammad RJ Mohammad - 1 year ago 78
Javascript Question

using reduce on a nested object

some one gave me this question as a practice problem. I have to use "_.reduce" on the following object to print out the text "a good practice". Quite frankly I am struggling even to visualize this in my head. Any help would be appreciated.

var test = {a:'a',b:{a:'good',c:{c:'practice'}}}

Thank You!

Answer Source

Because you don't know how nested the object is, you'll need to use recursion to accomplish the task at hand. You can't use .reduce on the object itself, so you'll have to use Object.keys to get an array of properties from the object. Then you can .reduce the returned array.

var test = {a:'a',b:{a:'good',c:{c:'practice'}}};
var deeperTest = {a:'a',b:{a:'deeper',b:{a:'test',b:{a:'than',b:{a:'before'}}}}};

function reducer(obj) {
  if (typeof obj != 'object') return ''; //we only want to reduce 'objects'
  return Object.keys(obj).reduce(function(prev, curr) {
    if (typeof obj[curr] != 'string')
      prev += ' ' + reducer(obj[curr]); //probably an object - let's dig in
      prev += ' ' + obj[curr]; //just a string - append to accumulator
    return prev;
  }, "");  


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download