My use case is something like this.
menu
dish_has_categories
dish_has_categories
array, if there is an object with CategoryId is equal to 8
I want to filter out that root object.My original data object
const data = [{
menuName: "Hot dogs",
menu: [
{
dishId: '1',
dish_has_categories: [{
CategoryId: '8'
}]
},
{
dishId: '2',
dish_has_categories: [{
CategoryId: '9'
}]
}]
},
{
menuName: "Burgers",
menu: [{
dishId: '3',
dish_has_categories: [{
CategoryId: '6'
}]
}, {
dishId: '4',
dish_has_categories: [{
CategoryId: '4'
}]
}]
},
{
name: "Drinks",
menu: []
}
]
My expect result is
[{
menuName: "Hot dogs",
menu: [
{
dishId: '1',
dish_has_categories: [{
CategoryId: '8'
}]
},
{
dishId: '2',
dish_has_categories: [{
CategoryId: '9'
}]
}]
}]
what I've done up to now is
const data2 = data.filter(element => {
return element.menu.length > 0
})
I have no idea how to deep filter inside nested objects and arrays. Hope my question is clear to you all.
You can use filter()
with nested some()
.
The
some()
method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value
const data = [{ menuName: "Hot dogs", menu: [ { dishId: '1', dish_has_categories: [{ CategoryId: '8' }] }, { dishId: '2', dish_has_categories: [{ CategoryId: '9' }] }] }, { menuName: "Burgers", menu: [{ dishId: '3', dish_has_categories: [{ CategoryId: '6' }] }, { dishId: '4', dish_has_categories: [{ CategoryId: '4' }] }] }, { name: "Drinks", menu: [] } ]
const res = data.filter(x =>
x.menu.some(y =>
y.dish_has_categories.some(z => z.CategoryId === '8')
)
);
console.log(res)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With