Search code examples
javascriptlodash

lodash for "select by object path"?


Let's say I have this object (or an array of these objects):

var person = {
    birth: {
        place: {
            country: 'USA'
        }
    }
};

I thought there was a lodash function where I could pass in 'birth.place.country' and get back the value USA.

Is there such a function in lodasdh 3.x, or am I Imagining this?


Solution

  • You could use the _.get function:

    _.get(person, 'birth.place.country', 'optionalDefaultValue');
    

    lodash also provides a function called _.result that can also call functions.