[英]JS: Filter array of objects by array, when object key is an array of objects
I have an array of objects that look similar to the following:我有一组类似于以下内容的对象:
let array = [
{
id: 1,
name: Foo,
tools: [{id:3, toolname: Jaw},{id:1, toolname: Law}]
},
{
id: 2,
name: Boo,
tools: [{id:2, toolname: Caw}]
},
{
id: 3,
name: Loo,
tools: [{id:3, toolname: Jaw}, {id:4, toolname: Maw}]
}
]
I am trying to filter objects from the above array using something similar to includes
against an existing array which looks like the following:我正在尝试使用类似于includes
对现有数组的内容从上述数组中过滤对象,该数组如下所示:
let secondarray = ['Jaw', 'Taw']
How would I return a list of objects which has a tool named within the second array?我将如何返回具有在第二个数组中命名的工具的对象列表?
Thanks for your time!谢谢你的时间!
I think you might use something like this:我想你可能会使用这样的东西:
let array = [
{
id: 1,
name: 'Foo',
tools: [{ id: 3, toolname: 'Jaw' }, { id: 1, toolname: 'Law' }]
},
{
id: 2,
name: 'Boo',
tools: [{ id: 2, toolname: 'Caw' }]
},
{
id: 3,
name: 'Loo',
tools: [{ id: 3, toolname: 'Jaw' }, { id: 4, toolname: 'Maw' }]
}
]
let secondarray = ['Jaw', 'Taw']
let filteredArray = array.filter(ch => {
let controlArray = ch.tools.map(t => t.toolname);
return secondarray.some(t => controlArray.includes(t));
});
console.log(filteredArray);
/**
which returns
[ { id: 1, name: 'Foo', tools: [ [Object], [Object] ] },
{ id: 3, name: 'Loo', tools: [ [Object], [Object] ] } ]
*/
You can use some()
with the tools
inside filter()
您可以将some()
与filter()
中的tools
一起使用
let array = [{id: 1,name: 'Foo',tools: [{id: 3,toolname: 'Jaw'}, {id: 1,toolname: 'Law'}]},{id: 2,name: 'Boo',tools: [{id: 2,toolname: 'Caw'}]},{id: 3,name: 'Loo',tools: [{id: 3,toolname: 'Jaw'}, {id: 4,toolname: 'Maw'}]}] let secondarray = ['Jaw', 'Taw'] let filtered = array.filter(item => item.tools.some(obj => secondarray.includes(obj.toolname))) console.log(filtered)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.