I'm trying to filter an array of objects based off a property and also filter an array of objects within. Can I use filter within a filter to loop through and reduce the second array?
Something like the following:
const menu = [
{
name: "Batman",
showinMenu: true,
categories: [
{
title: "Title 2",
showinMenu: true,
}
,
{
title: "Title 3",
showinMenu: false,
}
]
},
{
name: "Superman",
showinMenu: true,
categories: [
{
title: "Test 2",
showinMenu: true,
}
,
{
title: "Test 3",
showinMenu: false,
}
]
},
]
const Filtered = menu?.categories?.filter((category) => {
category.categories?.filter((subcategory) => {
return subcategory.showinMenu === true
})
return category.showinMenu === true
})
Expected output
[
{
name: "Batman",
showinMenu: true,
categories: [
{
title: "Title 2",
showinMenu: true,
}
]
}
]
CodePudding user response:
This is an immutable approach
const menu = [
{
name: "Batman",
showinMenu: true,
categories: [
{
title: "Title 2",
showinMenu: true,
}
,
{
title: "Title 3",
showinMenu: false,
}
]
},
{
name: "Superman",
showinMenu: true,
categories: [
{
title: "Test 2",
showinMenu: true,
}
,
{
title: "Test 3",
showinMenu: false,
}
]
},
]
let result = menu.filter(x=>x.showinMenu).map(y=>{
return {...y,categories:y.categories.filter(t=>t.showinMenu)}
})
console.log(result)
CodePudding user response:
You are not using the result of your second filter. This should do it:
const Filtered = menu?.categories?.filter((category) => {
return category.showinMenu === true
}).map((category) => {
if (!("categories" in category)) return category;
const filteredCategories = category.categories.filter((subcategory) => {
return subcategory.showinMenu === true
});
return { ...category, categories: filteredCategories };
});
CodePudding user response:
The inner filter will return a new array to stored somewhere so this won't work. Only outer filter will take effect in the final output.
The easiest way I can think of doing this will be to--
ans = []
for each obj in array:
if(condition is true):
clone this object and replace categories with filtered categories
add this cloned object to ans array