将不存在的项目推送到数组

时间:2016-04-19 22:50:45

标签: javascript arrays

所以我有这个数组:

os.system(command)

我需要显示按月分组的“总”数据。这意味着我必须在阵列上重复的月份(2016-03,2016-01)总计“总”金额。要找到解决方案,我需要理解为什么这个

var period = [{"total":852, "date":"2016-03"}, {"total":963, "date":"2016-03"},{"total":789,"date":"2016-02"},{"total":456,"date":"2016-04"},{"total":123,"date":"2016-01"},{"total":723,"date":"2016-01"}];

返回:

for ( var i = 0; i < period.length; i++ ){
 if (periodB.indexOf(period[i].date) == -1){
     periodB.push(period[i].date);  
 }

虽然这个:

  ["2016-03", "2016-02", "2016-04", "2016-01"]

归来这个:

for ( var i = 0; i < period.length; i++ ){
  if (periodB.indexOf(period[i].date) == -1){
  periodB.push({"date": period[i].date, "total": period[i].total});
  }
}

在第一个案例中,重复的“日期”没有被推到periodB数组,但是在第二个案例中它们是。

1 个答案:

答案 0 :(得分:0)

您可以使用临时对象和一个forEach循环

来解决您的任务
var obj = {};

period.forEach(e => {
    var month = e.date.split('-')[1]
    obj[month] = obj[month] + e.total || e.total
});

结果将是一个对象,其中月份为关键,总和为值

{
    '03': 1815, 
    '02': 789,
    '04': 456,
    '01': 846
}

工作示例:

&#13;
&#13;
var period = [{ "total": 852, "date": "2016-03" }, { "total": 963, "date": "2016-03" }, { "total": 789, "date": "2016-02" }, { "total": 456, "date": "2016-04" }, { "total": 123, "date": "2016-01" }, { "total": 723, "date": "2016-01" }];

var obj = {};

period.forEach(e => {
    var month = e.date.split('-')[1]
    obj[month] = obj[month] + e.total || e.total
});

document.write(JSON.stringify(obj, 0, 2));
&#13;
&#13;
&#13;