Skip to content
Advertisement

get array of object value and nested array of object value

I’ve this nested array of object array:

const items = [
    {
      id: 1,
      name: 'banana',
      selected: true,
    },
    {
      id: 2,
      subItems: [
        {
          id: '2a',
          name: 'apple',
          selected: true,
        },
        {
          id: '2b',
          name: 'orange',
          selected: false,
        },
      ],
    },
    {
      id: 3,
      name: 'watermalon',
      selected: true,
    },
    {
        id: 4,
        name: 'pear',
        selected: false,
      },
  ]

How can I get the ids base on selected property?

I manage to get the first level, I’ve tried

 const selectedItemId = items.map(item => item.selected && item.id).filter(Boolean)

but how can I select the ids which is in the subItems? I expect the result to be [1, '2a', 3]

Advertisement

Answer

Flatten the array first. Be careful of using && item.id inside the mapper because that’ll mean that falsey IDs (like 0, which is a reasonable starting number in some schemes) will be excluded.

const items=[{id:1,name:"banana",selected:!0},{id:2,subItems:[{id:"2a",name:"apple",selected:!0},{id:"2b",name:"orange",selected:!1}]},{id:3,name:"watermalon",selected:!0},{id:4,name:"pear",selected:!1}];

const output = items
  .flatMap(item => [item].concat(item.subItems ?? []))
  .filter(item => item.selected)
  .map(item => item.id);
console.log(output);
Advertisement