Javascript 合并数组中的重复对象并添加其他属性

Javascript 合并数组中的重复对象并添加其他属性,javascript,node.js,Javascript,Node.js,我有一个问题,我的代码基本上是试图合并重复的对象,并将附加属性“admin”设置为“true”,对于唯一的对象,将附加属性“admin”设置为“false” const addresses = [{name: 'Paul', id: 2}, {name: 'John', id: 1}, {name: 'John', id: 1}]; //combine duplicate object and add property admin: true let result = []; address

我有一个问题,我的代码基本上是试图合并重复的对象,并将附加属性“admin”设置为“true”,对于唯一的对象,将附加属性“admin”设置为“false”

const addresses = [{name: 'Paul', id: 2}, {name: 'John', id: 1}, {name: 'John', id: 1}];

//combine duplicate object and add property admin: true

let result = [];
addresses.forEach(elem => {
  let match = result.find(r => r.id === elem.id);
  if(match) {
    return {...match, ...elem, admin: true};
  } else {
    result.push({...elem, admin: false });
  }
});
但是我做得不对,因为我得到的输出是

const addresses = [{name: 'Paul', id: 2}, {name: 'John', id: 1}, {name: 'John', id: 1}];
您可以使用
array#reduce
对唯一地址进行分组,然后检查对象中的
admin
属性,并相应地分配值

const addresses=[{name:'Paul',id:2},{name:'John',id:1},{name:'John',id:1}],
用户=对象.值(地址.减少((r,o)=>{
r[o.id]={…o,admin:!r[o.id]};
返回r;
}, {}));
console.log(用户)使用

const addresses=[{name:'Paul',id:2},{name:'John',id:1},{name:'John',id:1}];
const result=addresses.reduce((a,o)=>({…a{
[o.id]:{…o,管理员:!a[o.id]}
}}), {});

console.log(Object.values(result))
您可以使用
reduce
创建一个唯一数组,将重复地址的
admin
属性设置为
true
,如下所示:

const addresses=[{name:'Paul',id:2},{name:'John',id:1},{name:'John',id:1}];
const result=地址。reduce((acc,地址)=>{
const dup=acc.find(addr=>addr.id==address.id);
如果(dup){
dup.admin=true;
返回acc;
}
address.admin=false;
返回acc.concat(地址);
}, [])

控制台日志(结果)
您正在修改
结果
而不是原始数组。请注意,
forEach
中的
return
没有任何意义!