需要根据主题名称属性对不同对象的 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将数组转换为对象,其中键作为名称,值作为结果对象。然后使用Object.values从创建的对象中收集所有值
- 创建对象时,检查对象中是否存在键(名称)。如果没有,请为其添加一个条目 (
a[name] = a[name] || {name};
)。 - 现在,对于所有其他键(subjects),使用 Object.entries 创建一个数组,并对其进行迭代以添加/更新 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}}];
var result = Object.values(data.reduce((a,{name, ...rest}) => {
a[name] = a[name] || {name};
Object.entries(rest).forEach(([k,v]) => {
a[name][k] = a[name][k] || {score:0, total_score:0};
a[name][k].score += v.score;
a[name][k].total_score += v.total_score;
});
return a;
},{}));
console.log(result);
关于javascript - 对对象类型数组的属性求和并将它们连接为单个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53590355/