Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

213
Vistas
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 Respuestas
Responde la pregunta

0

You can rely on flatMap:

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

  return x.items;
});
about 4 years ago · Juan Pablo Isaza Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda