我有这样的对象数组。

const array = [ { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 1, y: 2 }, { x: 3, y: 12 } ]

我想计算重复的对象并将其存储为新的对象字段。

我发现了此代码片段,它的效果很好,但并不是我所需要的。
const names = [{  _id: 1 }, { _id: 1}, { _id: 2}, { _id: 1}]

    const result = [...names.reduce( (mp, o) => {
    if (!mp.has(o._id)) mp.set(o._id, Object.assign({ count: 0 }, o));
    mp.get(o._id).count++;
    return mp;
    }, new Map).values()];

    console.log(result);

它与具有一个字段_id的对象一起使用。就我而言,有两个x和y

我应该如何修改该代码?

简而言之...我想收到结果:
result = [ { x: 1, y: 2, count:3 }, { x: 3, y: 4, count:2 }, { x: 3, y: 12, count:1 } ]

最佳答案

您可以使用Object.values()reduce()方法返回新的对象数组。

const array = [ { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 1, y: 2 }, { x: 3, y: 12 } ]

const result = Object.values(array.reduce((r, e) => {
  let k = `${e.x}|${e.y}`;
  if(!r[k]) r[k] = {...e, count: 1}
  else r[k].count += 1;
  return r;
}, {}))

console.log(result)


这是Map和扩展语法...的解决方案

const array = [ { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 1, y: 2 }, { x: 3, y: 12 } ]

const result = [...array.reduce((r, e) => {
  let k = `${e.x}|${e.y}`;
  if(!r.has(k)) r.set(k, {...e, count: 1})
  else r.get(k).count++
  return r;
}, new Map).values()]

console.log(result)

09-25 18:30
查看更多