Skip to content Skip to sidebar Skip to footer

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:

Solution 1:

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)

Solution 2:

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] ] } ]

*/

Post a Comment for "Js: Filter Array Of Objects By Array, When Object Key Is An Array Of Objects"