javascript - 如果对象中有重复值,则 JavaScript 求和值
问题描述
我有一个对象:
const transaction = [{
created: 1200,
amount: 200
},{
created: 1200,
amount: 400
},{
created: 1400,
amount: 400
},{
created: 1400,
amount: 300
},{
created: 1500,
amount: 100
}]
每次created
都具有相同的值,我想对amount
对象的 's 求和。因此,例如created: 1200
将有一个数量:600
总计,因为 multiplecreated
的位置在 1200 处,所以这个数量被加起来了。
解决方案
这是一个简单的解决方案,注意我编码很快,以便以后可以优化
const transaction = [{
created: 1200,
amount: 200
},{
created: 1200,
amount: 400
},{
created: 1400,
amount: 400
},{
created: 1400,
amount: 300
},{
created: 1500,
amount: 100
}];
// accepts an array of objects
function sumObj(objArr) {
// an object to store the `created` and `amount` as key=>value
var newObj = {};
// loop over the objects in the array
objArr.forEach(function(obj) {
// if the key is present in `newObj` then we need to add the amount to it's value
if(obj.created in newObj) {
newObj[obj.created] += obj.amount;
}else {
// else just add the key and the amount as value
newObj[obj.created] = obj.amount;
}
});
// create an array to store the final objects
var arr = [];
// loop over the properties in `newObj`
for(var prop in newObj) {
// push an object each time
arr.push({created: Number(prop), amount: newObj[prop]});
}
// return the final result
return arr;
}
// log it to see the output
console.log(sumObj(transaction));
注意:我注意到数组中的每个对象都是根据排序的,.created
所以我想出了另一个解决方案,请注意,如果对象并不总是排序,那么请改用第一个解决方案
const transaction = [{
created: 1200,
amount: 200
},{
created: 1200,
amount: 400
},{
created: 1400,
amount: 400
},{
created: 1400,
amount: 300
},{
created: 1500,
amount: 100
}];
// accepts an array of objects
function sumObj(objArr) {
// create an array to store the objects
var newArr = [];
// loop over the objects in the array
objArr.forEach(function(obj, ind, arr) {
// so since we check for the current object against the next one
// we need to check when there is no next one to avoid errors
// the idea is to check if the current object has the same .created
// of the next object then add the amount to the next object
// else check if this is the last object then just push it to the array
// or if the current object has a different .created value then
// just push it
if(ind === arr.length - 1 || obj.created !== arr[ind + 1].created) {
newArr.push(obj);
}else {
arr[ind + 1].amount += obj.amount;
}
});
// return the result
return newArr;
}
// print the result
console.log(sumObj(transaction));
推荐阅读
- c++ - TD[N] 是否总是声明数组类型的对象?
- java - 在maven插件中获取mojo参数
- swift - 获取错误的默认值
- excel - Excel如何在一列中循环所有数据
- python - 返回一年中特定日期的上个月
- swift - 不确定如何打开 uilabel 可选以计算我的 uilabels
- java - 如何仅对字符串值设置异常?
- node.js - 由于 MongoDB,Nodejs 无法调用多个 Web 应用程序实例
- node.js - 为什么当我没有调用时 console.log 会显示 CREATE TABLE 语句
- excel - 将 excel 中的许多列从 MS 转换为 HH:MM:SS 的宏