javascript - 对对象类型数组的属性求和并将它们作为单个对象加入
问题描述
需要根据主题名称属性对不同对象的score
和求和。total_score
输入数据 :
var data = [{
name: "One",
maths: {
score: 2,
total_score: 4
},
science: {
score: 2,
total_score: 4
},
social: {
score: 2,
total_score: 4
}
}, {
name: "One",
maths: {
score: 3,
total_score: 4
},
science: {
score: 1,
total_score: 4
},
english: {
score: 4,
total_score: 4
}
}]
预期输出:
{
name: "One",
maths: {
score: 5,
total_score: 8
},
science: {
score: 3,
total_score: 8
},
social: {
score: 2,
total_score: 4
},
english: {
score: 4,
total_score: 4
}
}
我试过这个:
data.forEach(function (a) {
if (!this[a.name]) {
this[a.name] = { name: a.name, contributions: 0 };
result.push(this[a.name]);
}
this[a.name].contributions += a.contributions;
}, Object.create(null));
但这不适用于我的情况。对象不同的地方,contributions
即主题名称每次都不同。
先谢谢各位了!
解决方案
您可以使用Array.reduce()
:
var data = [{
name: "One",
maths: {
score: 2,
total_score: 4
},
science: {
score: 2,
total_score: 4
},
social: {
score: 2,
total_score: 4
}
},
{
name: "One",
maths: {
score: 3,
total_score: 4
},
science: {
score: 1,
total_score: 4
},
english: {
score: 4,
total_score: 4
}
},
{
name: "Two",
maths: {
score: 3,
total_score: 4
},
science: {
score: 1,
total_score: 4
},
english: {
score: 4,
total_score: 4
}
},
{
name: "Two",
maths: {
score: 3,
total_score: 5
},
science: {
score: 1,
total_score: 5
},
english: {
score: 4,
total_score: 6
}
}
];
var res = data.reduce((acc, item)=>{
var exist = acc.find(({name}) => name === item.name);
if(exist){
Object.keys(item).forEach((key) =>{
if(key !== 'name'){
if(exist[key]){
exist[key].total_score += item[key].total_score;
exist[key].score += item[key].score
} else {
exist[key] = item[key]
}
}
});
} else {
acc.push(item);
}
return acc;
}, []);
console.log(res);
推荐阅读
- xml - XML 转换成 XML
- sql-server - 作业数据库和目标数据库是否需要位于不同的服务器上?
- javascript - 我收到错误消息:-未处理的拒绝(TypeError):无法读取 React 应用程序中未定义的属性“id”
- html - 如何水平滚动具有线性渐变效果的 div?
- python - Python:在行连接中间注释掉一行的任何变通方法
- linux - 如何在 Amazon Linux 或 Redhat 机器中使用 wget 使用许可接受选项下载 Nessus 代理
- firebase - 当我们在firestore中使用“添加”时,我们是否对写入和读取都收费?
- android - 如何在片段内的 Android 扩展上检测空指针异常的原因
- php - 如何从 Auth::attempt false return 获取更多信息?
- sql - 子查询与连接性能