繁体   English   中英

如何计算对象数组中属性的重复次数?

[英]How to count the number of repetitions of properties in an array of objects?

我需要计算每个 object 在数组中按 id 重复的次数,并创建新数组,该数组将具有 object 的“id”之类的值,数组中的重复次数为“count”。 我尝试使用reduce,但我认为使用错误。 尝试找到答案,但没有找到用对象创建新数组的变体。

// Array which I have

[
    { name: 'One', id: 3 },
    { name: 'Two', id: 1 },
    { name: 'Three', id: 2 },
    { name: 'Four', id: 1 }
]

// Array which I need to create

[
    { id: 3, count: 1 },
    { id: 1, count: 2 },
    { id: 2, count: 1 },
]

//I have try this code, but it return array with counts [1, 2, 1]

const results = Object.values(arr.reduce((acc, { id }) => {
 acc[id] = (acc[id] || 0) + 1;
 return acc;
}, {}));

谢谢!

你非常接近 - 你的reduce代码是正确的,但是你需要map你想要的 object 结构的条目:

 const input = [ { name: 'One', id: 3 }, { name: 'Two', id: 1 }, { name: 'Three', id: 2 }, { name: 'Four', id: 1 } ] const result = Object.entries(input.reduce((acc, { id }) => { acc[id] = (acc[id] || 0) + 1; return acc; }, {})).map( ([k,v]) => ({id: parseInt(k,10), count:v})); console.log(result);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM