![](/img/trans.png)
[英]How do I find objects with a property inside another object in JavaScript
[英]How do i find an object with specific property within nested objects
例如,我有一個Paths對象
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
}
}
};
我想根據ID獲取對象。
我嘗試這樣做_.find(Paths, {get:{id:1}})
但這里的id也可以在post對象中。
我需要一些幫助來解決lodash中的這個問題。
查找對象使用_.pickBy
var res = _.pickBy(Paths, function(path) {
return path.get.id === 1 || path.post.id === 1;
});
對於未知的密鑰
var res = _.pickBy(Paths, function(path) {
return _.chain(path)
.values()
.some(function(val) {
return _.get(val, 'id') === 1;
})
.value();
});
實際上,您的代碼很好,因為它只在get
而不是post
查找。 lodash還具有matchesProperty iteratee,在這種情況下,可以通過以下方式完成:
_.find(Paths, ["get.id", 1]);
另外,您可以按自定義函數進行過濾:
_.find(Paths, function(o) { return o.get.id == 2 || o.post.id == 2; });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.