lodash for “select by object path”?

笑着哭i 提交于 2020-01-22 17:31:04

问题


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?


回答1:


You could use the _.get function:

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

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




回答2:


Note: for an array of these objects

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

provides the same functionality as undefined's answer



来源:https://stackoverflow.com/questions/35207117/lodash-for-select-by-object-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!