简体   繁体   中英

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:

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()

 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)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM