Search code examples
javascriptlodash

Pick specific properties from nested objects


I have javascript objects which looks similar to this:

{
  id: 43,
  name: 'ajajaj'
  nestedObj1: {
    id: 53,
    name: 'ababab'
    foo: 'xxxx'
    nestedObj2: {
      id: 90,
      name: 'akakaka'
      foo2: 'sdsddd'
      surname: 'sdadasd'
      nestedObj3: {
        id: ..
        name: ..
        ...
      },
      objectsArr: [
        {id: .., name: ..., nestedOb4: {...} },
        {id: .., name: ..., nestedOb4: {...} }
      ]
    },
    foo0: ...
  }
  name: 'blabla'
}

Each objects which I have, has property id and name. My goal is pick all properties in first level, so properties of object with id 43 I pick all, and from every nested objects, I just pick properties id and name, and another will be thrown away.

I am using in project lodash, so I found function pick, but I don't know how to use this function for nested objects. Also note that nested objects could be also in array. Exist some elegant way for that please? Thanks in advice.


Solution

  • You can do this using recursion, as long as your objects do have an end to the levels of nesting. Otherwise, you run the risk of causing a stack limit error.

    function pickProperties(obj) {
        var retObj = {};
        Object.keys(obj).forEach(function (key) {
            if (key === 'id' || key === 'name') {
                retObj[key] = obj[key];
            } else if (_.isObject(obj[key])) {
                retObj[key] = pickProperties(obj[key]);
            } else if (_.isArray(obj[key])) {
                retObj[key] = obj[key].map(function(arrayObj) {
                    return pickProperties(arrayObj);
                });
            }
        });
        return retObj;
    }