0

Below is my object:

var obj = {
    'test': {
        'id1': 1,
        'id2': 2,
        'id3': 3
    }, 'test2': {
        'id4': 4,
        'id5': {
            'id123': 3,
            'id456': 6
        }
    },
    'test3': 45,
    'test4': 55
}

I am trying to write a recursive function for getting nested properties in the format like.

test.id1, test2.id5.id123 etc...

But I am not getting properties which are nested as shown above.

Below is my function

function getKey(obj, key) {
    var keyArr = [];
    var newKey = key;
    var data=newKey;

    if (_.isObject(obj[key])) {

      _.each(_.keys(obj[key]), function(singleKey) {
        newKey =  data + '.'+ getKey(obj[key], singleKey);
        return newKey
      });
    }

    return keyArr.length ? keyArr : newKey;   
  }

I am calling this function like var keys = _.keys(obj); _.each(keys, function(key) { getKey(obj, key); }

Can anyone help with this issue? Thanks

Pratik
  • 1,531
  • 3
  • 25
  • 57
  • 1
    Why are you using `_.each`? It doesn't return anything! – Bergi Apr 10 '15 at 12:45
  • @Bergi : Can you please suggest some solution ? – Pratik Apr 10 '15 at 17:56
  • I think you can do this yourself. Try to change the function signature so that `getKeys` takes only a single object and returns an array of joined key strings. You'll probably use two nested loops, one enumerating the object and one looping over the result of the recursive call. – Bergi Apr 10 '15 at 17:59
  • Thanks @Bergi. I will try and let you know... – Pratik Apr 10 '15 at 18:02

0 Answers0