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

128
Vistas
Merge Multiple Arrays Of The Same ID Into One Object

if two objects in the data array contains same id the first will be picked and the other(s) discarded. multiple assets of same id should be in one object.

const myMap = cardDetails.map((card) => {
      return {
        id: card.id,
        amount: Number(card.amount),
        quantity: card.quantity,
        images: card.file,
      };
    });

    const data = {
      id: user?.userid,
      data: myMap,
    };

My goal with this data is to merge the arrays (myMap) that contains same id into one object. How can this be achieved?

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

0

it's not clear what you mean with multiple assets

I assume that you want some key to be merge together

You can achieve that easily using reduce and Object.values

like this

const myData = Object.values(cardDetails.reduce((res, {id,...card}) => {
  const existing = res[id] || {}
  return {
    ...res,
    [id]: {
      id,
      ...existing,
      ...card //here you need to change accordingly with your merge logic     
    }
  }
}, {}));
about 4 years ago · Juan Pablo Isaza Denunciar

0

const groupData = (arr) => {
  const result = arr.reduce((acc, val) => {
    const existing = acc.find((obj) => obj.id == val.id)
    if (existing) {
     existing.data.push(val)
     }
     else {
      acc.push({ id: val.id, data: [val] })
     }
    
    return acc
  }, [])

  return result;
}

const arr = [
{id: 3, amount: 300, quantity: 77, images: ''}, 
{id: 3, amount: 400, quantity: 83, images: ''},
{id: 4, amount: 900, quantity: 48, images: ''}
]

console.log(groupData(arr))

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