循环遍历对象数组,并按对象元素ID返回每个总计值的总和 [英] Loop through array of objects and return sum of each total values by object element id
问题描述
我计算税款是一种非常复杂的开票方式.我无法解释整个过程,但是如果您有任何疑问,我会尽力回答.
I'm calculating taxes for a very complicate invoicing approach. I can't explain the whole process but if you have questions I will answer as best as I can.
我想出了JS中的对象数组:
I come up with an array of objects in JS:
[
{row_id: "20003859", expense_id: "429", tax_select: "tax1", tax_id: "1", tax_name: "GST 5%", tax_no: "", tax_value: "13.23"},
{row_id: "20003859", expense_id: "429", tax_select: "tax2", tax_id: "3", tax_name: "QST 9.975%", tax_no: "", tax_value: "26.38"},
{row_id: "20003840", expense_id: "409", tax_select: "tax1", tax_id: "1", tax_name: "GST 5%", tax_no: "", tax_value: "13.23"},
{row_id: "20003840", expense_id: "409", tax_select: "tax2", tax_id: "3", tax_name: "QST 9.975%", tax_no: "", tax_value: "26.38"},
{row_id: "20003870", expense_id: "419", tax_select: "tax1", tax_id: "2", tax_name: "HST 13%", tax_no: "", tax_value: "34.39"}
]
如您所见,我有3个tax_id:1、2和3.我可以有很多,但为简单起见,我只设置了3个.
As you can see I have 3 tax_ids: 1, 2 and 3. I can have many but for the sake of simplicity I put only 3.
我需要 遍历此对象数组并提出另一个对象数组 ,其总数按tax_id:
I need to loop through this array of objects and come up with another array of objects having the totals by tax_id:
[
{tax_name: "GST 5%", total_tax: sum of tax_value for tax_id = 1},
{tax_name: "QST 9.975%", total_tax: sum of tax_value for tax_id = 3},
{tax_name: "HST 13%", sum of tax_value for tax_id = 2}
]
此后,我可以遍历此数组并显示每个税项的总计,加上小计并显示总发票.
After that I can loop through this array and display the totals of each tax, adding subtotal and display the total invoice.
此外,我应该
Also, I should sort them by tax_select but this it's a thing I can live with.
我尝试过:其中selected_taxes是对象的第一个数组
I have tried to: where selected_taxes is the first array of objects
for (i = 0; i < selected_taxes.length; i++){
var sum = 0;
$.each( selected_taxes[i], function( tax_id, tax_value ) {
sum += tax_value;
});
console.log(sum);
}
但没有运气.
非常感谢您的帮助或建议.
Many thanks for your help or suggestions.
推荐答案
我认为Array.prototype.reduce
将是您最好的选择:
I think Array.prototype.reduce
will be your best bet for this:
var totals = data.reduce(function(c,x){
if(!c[x.tax_id]) c[x.tax_id] = {
tax_name: x.tax_name,
tax_id: x.tax_id,
total_tax: 0
};
c[x.tax_id].total_tax += Number(x.tax_value);
return c;
}, {});
此方法生成的对象具有其税号ID作为其属性.如果您真的想要一个平面数组,可以在事实之后将其转换为数组:
This approach generates an object that has, as its properties, the tax ID numbers. If you really want a flat array from that, you can convert that into an array after the fact:
var totalsArray = [];
for(var taxId in totals){
totalsArray.push(totals[taxId]):
}
演示: http://jsfiddle.net/3jaJC/1/
这篇关于循环遍历对象数组,并按对象元素ID返回每个总计值的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!