Search code examples
javascriptarraysnestedfiltering

JavaScript: how to filter a nested Object based on a string array?


I am a newbie to JavaScript. I have now a nested Object:

const fruitList = [
{   fruit: {id: '1-1', fruit_name: 'Apple'},
    location: {id: '2-1', location_name: 'USA'}
},
{
    fruit: {id: '1-2', fruit_name: 'Banana'},
    location: {id: '2-2', location_name: 'UK'}
},
{
    fruit: {id: '1-3', fruit_name: 'Orange'},
    location: {id: '2-1', location_name: 'USA'}
}
];

and a string array:

let keywords = ['Apple', 'Banana'];

I am trying to filter the nested Object based on the above string array and the expected outpust is :

output =[    
{   fruit: {id: '1-1', fruit_name: 'Apple'},
    location: {id: '2-1', location_name: 'USA'}
},
{
    fruit: {id: '1-2', fruit_name: 'Banana'},
    location: {id: '2-2', location_name: 'UK'}
}
];

I already tried:

const filteredFruit = fruitList.filter(({item})=>
    item.fruit?.fruit_name.every(ele => keywords.includes(ele))
)

but it didn't work. I also checked all the similar questions on the Stackoverflow, but still could not find a way to solve it. Thank you very much for your help!


Solution

  • You were close.

    1. item isn't a property of the object being iterated on so you can't destructure it.

    2. You need to swap around your condition to check to see if the keywords array includes the fruit name.

    const fruitList=[{fruit:{id:"1-1",fruit_name:"Apple"},location:{id:"2-1",location_name:"USA"}},{fruit:{id:"1-2",fruit_name:"Banana"},location:{id:"2-2",location_name:"UK"}},{fruit:{id:"1-3",fruit_name:"Orange"},location:{id:"2-1",location_name:"USA"}}];
    
    const keywords = ['Apple', 'Banana'];
    
    const filteredFruit = fruitList.filter(item =>
      keywords.includes(item.fruit.fruit_name)
    );
    
    console.log(filteredFruit);