我想比较两个对象以创建一个新对象。
original = [
{id: "A1", name: "Nick", age: 20, country: 'JP', code: 'PHP'}
]
edited = [
{name: "Mike", age: 30, country: 'US'},
{id: "A1", name: "Nick", age: 25, country: 'US', code: 'PHP'}
]
我想要的最终对象如下所示;
final = [
{name: "Mike", age: 30, country: 'US'},
{id: "A1", age: 25, country: 'US'}
]
我一直在尝试使用过滤器,但是我没有得到想要的结果...
答案 0 :(得分:0)
尝试使用Array#reduce
。
已更新,且所有密钥对都匹配
Array#map
和indexOf
函数验证原始数组中已编辑的数组id值可用{key:[value]}
var original = [{id: "A1", name: "Nick", age: 20, country: 'JP'}];
var edited = [{name: "Mike", age: 30, country: 'US'},{id: "A1", name: "Nick", age: 25, country: 'US'}];
var ids_org = Object.keys(original[0]).reduce((a,b,c)=> (a[b]=original.map(a=> a[b]),a),{});
var res = edited.reduce((a, b) => {
if (b.id) {
Object.keys(b).forEach(i=>{
if(ids_org[i].indexOf(b[i]) > -1 && i != 'id')
delete b[i];
})
a.push(b);
} else {
a.push(b);
}
return a;
}, []);
console.log(res)
答案 1 :(得分:-1)
使用解构从对象中提取ID。 使用lodash isEqual方法进行比较,然后再将id添加回该对象。