For example, I have a Paths object
var Paths = {
path1: {
name: 'method1',
get: {
name: 'param1',
id: 1
},
post: {
name: 'param2',
id: 2
}
},
path2: {
name: 'method2',
get: {
name: 'param1',
id: 3
},
post: {
name: 'param2',
id: 4
}
}
};
I want to get the object based on the id.
I tried doing this _.find(Paths, {get:{id:1}})
But here id can also be in post object.
I need some help in solving this problem in lodash .
to find in object use _.pickBy
var res = _.pickBy(Paths, function(path) {
return path.get.id === 1 || path.post.id === 1;
});
for unknown key
var res = _.pickBy(Paths, function(path) {
return _.chain(path)
.values()
.some(function(val) {
return _.get(val, 'id') === 1;
})
.value();
});
Actually, your code is good as it is looking only inside get
, not post
. lodash also has matchesProperty iteratee which, in this case, could be done this way:
_.find(Paths, ["get.id", 1]);
Also, you can filter by custom functions:
_.find(Paths, function(o) { return o.get.id == 2 || o.post.id == 2; });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.