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

124
Vistas
Merge array of objects preserving some key-values php

Consider the following two arrays:

[
{
    id: jhz,
    name: 'John',
    eyes: 'Green',
    description: 'Cool guy',
},
{
    id: mbe,
    name: 'Mary',
    brand: 'M&B',
    text: 'Something',  
}
]
[
{
    id: jhz,
    name: 'John',
    eyes: '',
},
{
    id: mbe,
    name: 'Mary',
},
{
    id: 'beh',
    name: 'Bernard',
}
]

First array may have any kind of key value pairs, but it will always have the key id and name. I want to merge the two arrays by taking id and name into account and preserving them, while merging everything else and replacing them with data from the first array if any keys duplicate.

Also tricky part - the merged array needs to follow the order of the second array.

So in this example the result I'm looking for is:

[
{
    id: jhz,
    name: 'John',
    eyes: 'Green',
    description: 'Cool guy',
},
{
    id: mbe,
    name: 'Mary',
    brand: 'M&B',
    text: 'Something',  
},
{
    id: 'beh',
    name: 'Bernard',
}
]
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

you can do something like this using Array.map

const data1 = [{
    id: 'jhz',
    name: 'John',
    eyes: 'Green',
    description: 'Cool guy',
  },
  {
    id: 'mbe',
    name: 'Mary',
    brand: 'M&B',
    text: 'Something',
  }
]


const data2 = [{
    id: 'jhz',
    name: 'John',
    eyes: '',
  },
  {
    id: 'mbe',
    name: 'Mary',
  },
  {
    id: 'beh',
    name: 'Bernard',
  }
]

const result = data2.map(d => ({...d, ...(data1.find(d1 => d1.id === d.id && d1.name === d.name) || {})}))

console.log(result)

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