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

127
Visualizações
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 Respostas
Responde à pergunta

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 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