Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

126
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!