简体   繁体   中英

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',
}
]

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM