Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 868
core Avatar asked Feb 04 '16 17:02

core


2 Answers

You could use the _.get function:

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

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

like image 88
undefined Avatar answered Oct 19 '22 23:10

undefined


Note: for an array of these objects

_.map(people, 'birth.place.country')

provides the same functionality as undefined's answer

like image 45
Bash4life Avatar answered Oct 19 '22 21:10

Bash4life