Reputation: 327
Javascript. Have a structure like this, array of objects, that have array of items
inside each
[
{
"title": "Venom",
"items": [
{
"title": "Venom title",
"active": true
},
{
"title": "Venom2",
"active": false
}
]
},
{
"title": "Video",
"items": []
},
{
"title": "Button",
"items": [
{
"title": "Button page",
"active": true
}
]
}
]
I want to exclude items
with active: false
property inside each element, so exclude element Venom2
{
"title": "Venom2",
"action": "venom2",
"content": "qwertrete5t5t4t5",
"active": false
}
from exists array.
I make it with forEach and accumulate array inside another, here it is
let menu = [];
v.forEach((section) => {
menu.push({
title: section.title,
items: section.items.filter(item => item.active)
})
});
Then I tried to make it more beautiful with double filter, but it's not working, it returns []
, and i basically guess why...
let menu = v.filter((section) => {
return (section.items.filter(item => item.active === true));
});
Perhaps there are more beautiful (may be with reduce) decision of my case?
Upvotes: 0
Views: 176
Reputation: 35222
Your forEach
should work fine. The only improvement I can see is to use map
and destructuring. So that, you can directly assign it to menu
like this:
const v = [{title:"Venom",items:[{title:"Venom title",active:true},{title:"Venom2",active:false}]},{title:"Video",items:[]},{title:"Button",items:[{title:"Button page",active:true}]}];
let menu = v.map(({title, items}) => ({title, items: items.filter(i => i.active)}))
console.log(menu)
Upvotes: 1