如何计算数组中的相同对象属性值 [英] how to count same object attribute values in array
问题描述
我有一个大型数组,结构如下:
I have a large array with the following structure:
let data = [
{
name: 'name1',
values: {...},
},
{
name: 'name1',
values: {...},
},
{
name: 'name2',
values: {...},
},
{
name: 'name1',
values: {...},
},
{
name: 'name3',
values: {...},
},
...
]
我需要找到一种方法来计算每个名称在数据数组中作为名称值出现的频率。
I need to find a way to count how often each name appears as a name value inside the data array.
所以在这个例子中,结果应该类似于以下数组:
So in this example the result should look like the following array:
let nameCounts = [
{
name: 'name1'
count: 3
},
{
name: 'name2'
count: 1
},
{
name: 'name3'
count: 1
}
]
我很难找到好的wa你这个问题。有什么想法?
I'm struggling to find good way for this problem. Any ideas?
推荐答案
你可以 reduce
将数组转换为名称为键的对象将对象计为值。然后,您可以使用 <$获取最终数组。 c $ c> Object.values :
let data = [{
name: 'name1',
values: {},
},
{
name: 'name1',
values: {},
},
{
name: 'name2',
values: {},
},
{
name: 'name1',
values: {},
},
{
name: 'name3',
values: {},
}
];
var res = Object.values(data.reduce((a, {name}) => {
a[name] = a[name] || {name, count: 0};
a[name].count++;
return a;
}, Object.create(null)));
console.log(res);
请注意,我使用对象解构从reduce回调中的每个当前对象获取 name
值。并且 ||
模式是JS land中的标准做法,如果它不存在则指定默认值。
Note that I use object destructuring to get the name
value from each "current" object in the reduce callback. And the ||
pattern is standard practice in JS land to assign a default if it's not present.
另请注意@ ibrahimmahrir关于使用 Object.create(null)
为累加器创建无原型对象的注释。
Also note @ibrahimmahrir's comment about using Object.create(null)
to create a prototypeless object for the accumulator.
这篇关于如何计算数组中的相同对象属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!