通过嵌套数组中的match属性查找对象 [英] Find object by match property in nested array
问题描述
当我的条件涉及嵌套数组时,我看不到find
对象的方法.
I'm not seeing a way to find
objects when my condition would involve a nested array.
var modules = [{
name: 'Module1',
submodules: [{
name: 'Submodule1',
id: 1
}, {
name: 'Submodule2',
id: 2
}
]
}, {
name: 'Module2',
submodules: [{
name: 'Submodule1',
id: 3
}, {
name: 'Submodule2',
id: 4
}
]
}
];
这将不起作用,因为submodules
是一个数组,而不是一个对象.是否有任何速记可以使这项工作奏效?我试图避免手动迭代数组.
This won't work because submodules
is an array, not an object. Is there any shorthand that would make this work? I'm trying to avoid iterating the array manually.
_.where(modules, {submodules:{id:3}});
推荐答案
这是我想出的:
_.find(modules, _.flow(
_.property('submodules'),
_.partialRight(_.some, { id: 2 })
));
// → { name: 'Module1', ... }
使用 flow(),您可以构造执行所需功能的回调函数.调用时,数据流通过每个函数.您需要的第一件事是submodules
属性,您可以使用 property()函数获得它
Using flow(), you can construct a callback function that does what you need. When call, the data flows through each function. The first thing you want is the submodules
property, and you can get that using the property() function.
然后将submodules数组输入 some(),如果包含子模块,则返回true在这种情况下,您使用的是ID 2
.
The the submodules array is then fed into some(), which returns true if it contains the submodule you're after, in this case, ID 2
.
如果要查找多个模块,而不仅仅是找到的第一个模块,请用filter()
替换find()
.
Replace find()
with filter()
if you're looking for multiple modules, and not just the first one found.
这篇关于通过嵌套数组中的match属性查找对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!