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

130
Vistas
Move objects in array where duplicates occur

I have an array of objects, each array has a key of name and then another array of objects:

const myArray = [ { name: "1", item: [{}] }, { name: "2", item: [{}] }, { name: "1", item: [{}] } ]

Now for example sometimes that name key will be the same, i want to be able to check if that name exists and if it does exist push the item into that array object and not into a new object.

The behaviour im getting is above but i would like:

const myArray = [ { name: "1", item: [{ item1, item2 etc }] }, { name: "2", item: [{}] }, { name: "3", item: [{}] } ]

Thanks so much in advance!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can get the desired result using Array.reduce(), grouping by name.

If two objects in myArray share the same name, the item values are combined.

const myArray = [ { name: "1", item: [{ id: 1 }] }, { name: "2", item: [{ id: 2}] }, { name: "1", item: [{ id: 3}] } ]

const result = Object.values(myArray.reduce((acc, { name, item }) => { 
    acc[name] = acc[name] || { name, item: [] };
    acc[name].item.push(...item);
    return acc;
}, {}))

console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }

about 4 years ago · Juan Pablo Isaza Denunciar

0

Here's a solution using Array.prototype.reduce function.

const myArray = [ { name: "1", item: [{}] }, { name: "2", item: [{}] }, { name: "1", item: [{}] } ];

const output = myArray.reduce((acc, curr) => {
  const index = acc.findIndex(pre => pre.name === curr.name);
  if(index !== -1) {
    acc[index].item = acc[index].item.concat(curr.item);
  } else {
    acc.push(curr);
  }
  
  return acc;
}, []);

console.log(output);

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