简体   繁体   English

合并保留一些键值的对象数组php

[英]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 .第一个数组可能有任何类型的键值对,但它总是有键idname 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.我想通过考虑idname保留它们来合并两个数组,同时合并其他所有内容,如果有任何键重复,则用第一个数组中的数据替换它们。

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你可以使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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