在一个数组对象中,对象有很多个属性,如果对象中其中一个属性的的值相同,则加总相同键下面的数值,使用js写个例子
时间: 2024-05-04 15:15:41 浏览: 109
当然,我很乐意回答你的问题。以下是一个使用 JavaScript 对象和数组的示例代码,以实现相同属性值的对象的加总:
```javascript
// 创建一个包含多个对象的数组
var arr = [
{ name: 'Alice', age: 30, score: 80 },
{ name: 'Bob', age: 25, score: 90 },
{ name: 'Charlie', age: 35, score: 70 },
{ name: 'Alice', age: 30, score: 70 },
{ name: 'Bob', age: 25, score: 80 }
];
// 创建一个空对象,用于保存加总后的结果
var result = {};
// 遍历数组中的每个对象
arr.forEach(function(obj) {
// 创建一个键,由 name 和 age 属性组成
var key = obj.name + obj.age;
// 如果这个键不存在于结果对象中,就新建一个键,并将当前对象的 score 属性的值赋给它
if (!result[key]) {
result[key] = obj.score;
}
// 如果这个键已经存在于结果对象中,就将当前对象的 score 属性的值加到它上面
else {
result[key] += obj.score;
}
});
// 输出结果对象
console.log(result);
```
这段代码将数组中的对象按照 name 和 age 属性的值相同的对象进行加总,并将加总后的结果存储在一个新的对象中。如果你有任何关于这段代码的问题,请随时问我。
阅读全文
相关推荐














