我正在尝试使用javascript迭代对象,并将属性分组的值与另一个属性的值相加。这是我正在迭代的示例数据:
63.450, 2013-01-01 00:00:00, 63.450, 2013, Amex Residuals
3.980, 2013-01-01 00:00:00, 3.980, 2013, Gift Cards on Demand
-16.000, 2013-01-01 00:00:00, -16.000, 2013, Month End Fee Rejects
67.140, 2013-02-01 00:00:00, 67.140, 2013, Amex Residuals
-600.000, 2013-02-01 00:00:00, -600.000, 2013, Bonus Take Back - Closed Less Than 6 Months
-400.000, 2013-02-01 00:00:00, -400.000, 2013, Bonus Take Back - Did Not Activate
8.910, 2013-02-01 00:00:00, 8.910, 2013, Checks On Demand
13997.770, 2013-02-01 00:00:00, 13997.770, 2013, Global Report
-15.000, 2013-02-01 00:00:00, -15.000, 2013, Merchant Adjustments
-34.500, 2013-02-01 00:00:00, -34.500, 2013, Month End Fee Rejects
数据继续包括第二栏中的其他月份(至十月)。我需要将每个不同月份的第一列中的所有值汇总在一起,并从第4列创建一个javascript日期,因此结果应该是这样的:
var data = [ [Date.UTC('2013', i, 1), parseFloat('51.43')], [Date.UTC('2013', i, 1), parseFloat(13024.32)] ];
基本上我应该每个月最终得到一个2元素数组,总共使用第4列的日期对象。我只是不确定如何对第二列(日期)的条件分组进行求和的迭代。
答案 0 :(得分:1)
一般过程是:
在不知道确切结构的情况下,这里有一些半伪代码
var data = {}
for (var i = 0; i < lines.length; ++i) {
var monthYear = lines[i][1].substring(0, 6);
var value = 0;
if (data[monthYear]) {
value = data[monthYear];
}
value += +lines[i][0]; // unary + to make sure the value is a number, not a string
data[monthYear] = value;
}
(显然,如果你有对象而不是数组,你可以适当地访问它们。)
答案 1 :(得分:1)
根据@ scottmermelstein的回答(我会接受,因为它引导我这个)我创建了以下内容,它给了我正在寻找的结果:
var objCalc = {'unCalc':{}, 'reCalc':{}},
objUnCalc = {},
objReCalc = {},
arrUnCalc = [],
arrReCalc = [];
//lets sum up the month totals first, and create the date object that is needed for the graph
$.each(data.TableContainer, function(i,e){
objCalc.unCalc[ e.ActualDate ] = ( objCalc.unCalc[ e.ActualDate ] ? objCalc.unCalc[ e.ActualDate ] + parseFloat(e.GrpTotal) : parseFloat(e.GrpTotal) );
objCalc.reCalc[ e.ActualDate ] = ( objCalc.reCalc[ e.ActualDate ] ? objCalc.reCalc[ e.ActualDate ] + parseFloat(e.GrpBonusAmt) : parseFloat(e.GrpBonusAmt) );
});
//now we iterate over the summed values from above and push them to usable highcharts arrays
$.each(objCalc, function(i,e){
$.each(e, function(y,el){
var arrDate = y.substring(0,y.indexOf(' ')).split('-'), //renders something like ['2013','02','01']
UTC = Date.UTC(arrDate[0], parseInt(arrDate[1])-1, parseInt(arrDate[2])), //subtract 1 from month to make UTC date 0-based
arr = [ UTC, parseFloat( parseFloat( el ).toFixed( 2 ) ) ];
if( i == "unCalc" ) arrUnCalc.push( arr );
if( i == "reCalc" ) arrReCalc.push( arr );
});
});