0

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?

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.