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

210
Visualizações
Flatten array of items into the middle of another array

I have an array like so

let items = [
  {name: "1"},
  {name: "2"},
  {name: "3"},
  {unwrap: true,
    items: [
      {name: "4"},
      {name: "5"},
      {name: "6"},
    ]
  },
  {name: "7"},
]

How can I flatten the unwrap object to get the following output?

items = [
  {name: "1"},
  {name: "2"},
  {name: "3"},
  {name: "4"},
  {name: "5"},
  {name: "6"},
  {name: "7"},
]

I thought I could do something like this:

items.map(item => {
  if(item.hasOwnProperty("unwrap")){
    return ... item.items
  }
  return item
})

However the ...s don't work as a return value.

I have come up with the somewhat clunky using a second array like so:

let output = []
items.forEach((item) => {
    if (!item) {
        return;
    }
    if (item.hasOwnProperty("unwrap")) {
        return output.push(...item.contents);
    }
    return output.push(item);
});
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can rely on flatMap:

items.flatMap((x) => {
  if (!x.unwrap) {
    return x;
  }

  return x.items;
});
about 4 years ago · Juan Pablo Isaza Relatório

0

flatMap is what you need.

const items=[{name:"1"},{name:"2"},{name:"3"},{unwrap:!0,items:[{name:"4"},{name:"5"},{name:"6"}]},{name:"7"}];

const result = items.flatMap(item => {
  if (item.hasOwnProperty('unwrap')) {
    return item.items;
  }
  return item;
});

console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

Another way using reduce()

let items = [{name: "1"}, {name: "2"}, {name: "3"}, {unwrap: true, items: [{name: "4"}, {name: "5"}, {name: "6"}, ] }, {name: "7"}, ];

const res = items.reduce((p, c) => p.concat(c.items || c), []);

console.log(res);

Since obj.items won't exist on the regular objects, we can use the || operator to get the desired items, then concat those to the final array.

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