bas*_*tej 3 javascript ecmascript-6
我有这样的对象数组。
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 } ]
Run Code Online (Sandbox Code Playgroud)
我想计算重复对象并将计数存储为新对象字段。
我发现了这个片段,它工作得很好,但它不完全是我需要的。
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);
Run Code Online (Sandbox Code Playgroud)
它适用于具有一个字段 _id 的对象。就我而言,有两个,x 和 y
我应该如何修改该代码?
简而言之......我想收到结果:
result = [ { x: 1, y: 2, count:3 }, { x: 3, y: 4, count:2 }, { x: 3, y: 12, count:1 } ]
Run Code Online (Sandbox Code Playgroud)
您可以使用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)Run Code Online (Sandbox Code Playgroud)
这是带有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)Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1958 次 |
| 最近记录: |