我想要显示单个项目的名称及其总和。你能帮帮我吗?
const meals = [
{ calorie: 10,
diet: 'Chicken',
day: 1
},
{ calorie: 15,
diet: 'Soya',
day: 2
},
{ calorie: 20,
diet: 'Chicken',
day: 3
},
{ calorie: 25,
diet: 'Soya',
day: 4
}
];我的输出:饮食总和(鸡肉)= 30 (10 + 20)饮食总和(大豆)= 40 (15 +25)我想显示饮食名称和总卡路里,如下所示。
Chicken = 30
Soya = 40发布于 2020-12-04 22:36:52
您可以使用带有对象的Array#reduce来存储每个饮食的总和。
const meals = [
{ calorie: 10,
diet: 'Chicken',
day: 1
},
{ calorie: 15,
diet: 'Soya',
day: 2
},
{ calorie: 20,
diet: 'Chicken',
day: 3
},
{ calorie: 25,
diet: 'Soya',
day: 4
}
];
const res = meals.reduce((acc,{calorie, diet})=>
(acc[diet]=(acc[diet] || 0) + calorie, acc),{});
for(const key in res){
console.log(key,'=',res[key]);
}
发布于 2020-12-04 22:36:28
您可以使用Array.reduce()方法。
const meals = [{
calorie: 10,
diet: 'Chicken',
day: 1
},
{
calorie: 15,
diet: 'Soya',
day: 2
},
{
calorie: 20,
diet: 'Chicken',
day: 3
},
{
calorie: 25,
diet: 'Soya',
day: 4
}
];
const output = meals.reduce((acc, cur) => {
if (!acc[cur.diet]) acc[cur.diet] = 0;
acc[cur.diet] += cur.calorie
return acc;
}, {});
console.log(output);
发布于 2020-12-04 22:42:06
总和可以使用Array.reduce来实现
const meals = [{calorie:10,diet:'Chicken',day:1},{calorie:15,diet:'Soya',day:2},{calorie:20,diet:'Chicken',day:3},{calorie:25,diet:'Soya',day:4}]
const calculateSum = (data) => data.reduce((res, {
calorie,
diet
}) => {
//Add/update the object with key as `diet`
//sum up the calories with the previous value,
//if the object is not present in the `res` object then add the calories to `0`
res[diet] = (res[diet] || 0) + calorie;
return res;
}, {})
console.log(calculateSum(meals));
一旦对象形成,它就可以以所需的格式显示。
https://stackoverflow.com/questions/65145451
复制相似问题