Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

134
Visualizações
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]

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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);

about 4 years ago · Juan Pablo Isaza Relatório

0

You can recursively traverse all the items and select the items that have selected set to true.

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 },
];

function getSelectedItems(items, selectedItems = []) {
  for (let item of items) {
    if (item.subItems) {
      getSelectedItems(item.subItems, selectedItems);
    } else if (item.selected) {
      selectedItems.push(item.id);
    }
  }
  return selectedItems;
}

console.log(getSelectedItems(items));

about 4 years ago · Juan Pablo Isaza Relatório

0

 let newArray = [];
items.forEach(i=>{
    if(i.selected){
    newArray.push(i.id)
    }
    if(i.subItems){
    i.subItems.forEach(j=>{
        if(j.selected){
        newArray.push(j.id)
        }
    })
}
});

so this is bit lengthy. with 2 map loops

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda