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

时间:2019-07-20 11:41:51

标签: 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 = [];
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}];

3 个答案:

答案 0 :(得分:0)

您可以使用array#reduce对唯一地址进行分组,然后检查对象中的admin属性并相应地分配值。

const addresses = [{name: 'Paul', id: 2}, {name: 'John', id: 1}, {name: 'John', id: 1}],
      users = Object.values(addresses.reduce((r,o) => {
        r[o.id] = {...o, admin: !r[o.id]};
        return r;
      }, {}));
console.log(users);

答案 1 :(得分:0)

使用reduce()

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

const result = addresses.reduce((a, o) => ({...a, ...{
  [o.id]: { ...o, admin: !a[o.id] }
}}), {});

console.log(Object.values(result));

答案 2 :(得分:0)

您可以使用reduce创建一个唯一的数组,该数组将重复地址的admin属性设置为true,如下所示:

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

const result = addresses.reduce((acc, address) => {
  const dup = acc.find(addr => addr.id === address.id);
  if (dup) {
    dup.admin = true;
    return acc;
  }
  address.admin = false;
  return acc.concat(address);
}, [])

console.log(result);