我正在尝试迭代具有相似键值的对象数组,并且想要计算它们的值在整个对象数组中重复的次数,例如在整个对象中计算“晚餐”
var objects = [
{ Ram: 'Lunch', Luv:'Lunch', Rani:'Dinner' },
{ Ram: 'Dinner', Luv:'Lunch', Rani:'Dinner' },
{ Ram: 'Lunch', Luv:'Dinner', Rani:'Dinner' }
];
我正在尝试计算午餐发生了多少次以及晚餐发生了多少次,并希望在这样的json下面显示 -
[{'Dinner':5}, {'Lunch':4}];
我如何在javascript中实现这一目标?
答案 0 :(得分:2)
您可以将reduce()
与Object.values()
一起使用,并返回一个对象而不是对象数组。
var objects=[
{Ram:'Lunch', Luv:'Lunch', Rani:'Dinner'},
{Ram:'Dinner', Luv:'Lunch', Rani:'Dinner'},
{Ram:'Lunch', Luv:'Dinner', Rani:'Dinner'}
]
const result = objects.reduce((r, o) => {
Object.values(o).forEach(e => r[e] = (r[e] || 0) + 1)
return r;
}, {});
console.log(result)
答案 1 :(得分:1)
因为我不喜欢forEach
,所以这里是 double-reduce :
const objects = [
{ Ram: 'Lunch', Luv: 'Lunch', Rani: 'Dinner' },
{ Ram: 'Dinner', Luv: 'Lunch', Rani: 'Dinner' },
{ Ram: 'Lunch', Luv: 'Dinner', Rani: 'Dinner' }
];
const count = objects
// collect and flatten object values
.reduce((a, o) => a.concat(Object.values(o)), [])
// count individual
.reduce((c, v) => ({...c, [v]: (c[v] || 0) + 1}), {})
;
const list = Object.entries(count)
// map to {type, count}
.map(([type, count]) => ({type, count}))
;
console.log(count, list);
答案 2 :(得分:0)
将reduce
与forEach
var output = objects.reduce( (a, c) =>
(Object.values(c).forEach(
s => a[s] = (a[s] || 0) + 1 ), //end forEach
a),
{})//end reduce
<强>演示强>
var objects = [{
Ram: "Lunch",
Luv: "Lunch",
Rani: "Dinner"
},
{
Ram: "Dinner",
Luv: "Lunch",
Rani: "Dinner"
},
{
Ram: "Lunch",
Luv: "Dinner",
Rani: "Dinner"
}
];
var output = objects.reduce((a, c) => (Object.values(c).forEach(s => a[s] = (a[s] || 0) + 1), a), {});
console.log(output);