我有一个具有两个不同值的对象数组,我想要根据键值求总或这些值。如何使其正常运行?请帮助并提前致谢。
var GetFinancial = function() {
var promises = [];
fnancialObj = {};
/* calculate total for Firsr*/
let productAdsPaymentEventListArr = [{ "CurrencyAmount": "300" },{ "CurrencyAmount": "200"} ]
let productAdsTotal = 0;
productAdsPaymentEventListArr.forEach(function(productAdsPaymentEventListItem, index) {
let valueType = 'productAdsPaymentTotal'
promises.push(GetFinancialEventWithTotal(productAdsPaymentEventListItem.CurrencyAmount, productAdsTotal, fnancialObj, valueType))
})
/* calculate total of second*/
let productAdsPaymentEventListArr2 = [{ "CurrencyAmount": "30"},{ "CurrencyAmount": "20"} ]
let productAdsTotal2 = 0;
productAdsPaymentEventListArr2.forEach(function(productAdsPaymentEventListItem2, index) {
let valueType = 'productAdsPaymentTotal2'
promises.push(GetFinancialEventWithTotal(productAdsPaymentEventListItem2.CurrencyAmount, productAdsTotal2, fnancialObj, valueType))
})
Promise.all(promises).then(function(result) {
console.log("product update or inserted successfully in all ", result)
resolve(result)
}).catch(function(err) {
console.log("err in update or inserted in all promise", err)
})
}
Promice Defination在这里:
var GetFinancialEventWithTotal = function(chargeComponent, totalCharge, fnancialObj, objectKey) {
return new Promise(function(resolve, reject) {
totalCharge = totalCharge + parseFloat(chargeComponent);
if (totalCharge) {
fnancialObj[objectKey] = totalCharge;
resolve(fnancialObj);
} else {
reject("There an Error")
}
})
}
我想要这样的输出(根据键值将每个数组的每个值相加):
fnancialObj={
productAdsPaymentTotal : 500,
productAdsPaymentTotal2 :50,
}
最佳答案
除非工作流程中有异步操作,否则您不需要任何Promises。对于您当前的问题,您只需要将金额添加到对象数组中即可。这就是reduce()
的用途。在每个数组上调用reduce()
以获取总和并返回具有两个结果的对象。
var GetFinancial = function() {
/* calculate total for Firsr*/
let productAdsPaymentEventListArr = [{ "CurrencyAmount": "300" },{ "CurrencyAmount": "200"} ]
let productAdsTotal = productAdsPaymentEventListArr.reduce((total, current) => total + parseInt(current.CurrencyAmount), 0);
/* calculate total of second*/
let productAdsPaymentEventListArr2 = [{ "CurrencyAmount": "30"},{ "CurrencyAmount": "20"} ]
let productAdsTotal2 = productAdsPaymentEventListArr2.reduce((total, current) => total + parseInt(current.CurrencyAmount), 0);
return {
productAdsPaymentTotal : productAdsTotal,
productAdsPaymentTotal2 :productAdsTotal2,
}
}
let financials = GetFinancial()
// do any further calculations you want with financials
console.log(financials)
关于javascript - 如何使用Promise获得总计相同的键值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52862271/