JavaScript中的聚合对象属性

时间:2014-08-20 18:59:15

标签: javascript jquery arrays object sum

我想在一个对象数组中聚合属性,并生成另一个具有总数的对象。

以下是我正在处理的一个例子:

下面是一个对象数组,我们需要根据displayAd_imp范围求和 videoAd_imptv_impWeekNo

var objArr = [{

    "Title": "July 13 - July 19 2014",
    "displayAd_imp": "15",
    "videoAd_imp": "75",
    "tv_imp": "120",
    "Date": "2014-07-17T00:00:00.000Z",
    "WeekNo": 29
}, {

    "Title": "July 20 - July 26 2014",
    "displayAd_imp": "25",
    "videoAd_imp": "65",
    "tv_imp": "130",
    "Date": "2014-07-24T00:00:00.000Z",
    "WeekNo": 30
}, {

    "Title": "July 27 - Aug 2 2014",
    "displayAd_imp": "35",
    "videoAd_imp": "55",
    "tv_imp": "140",
    "Date": "2014-07-31T00:00:00.000Z",
    "WeekNo": 31
}, {

    "Title": "Aug 3 - Aug 9 2014",
    "displayAd_imp": "55",
    "videoAd_imp": "25",
    "tv_imp": "20",
    "Date": "2014-08-07T00:00:00.000Z",
    "WeekNo": 32
}, {

    "Title": "Aug 10 - Aug 17 2014",
    "displayAd_imp": "10",
    "videoAd_imp": "70",
    "tv_imp": "120",
    "Date": "2014-08-14T00:00:00.000Z",
    "WeekNo": 33
}]

以下功能获取范围。我们将数据,开始周和结束周传递为params,并按所需范围过滤数据。我有一个JSfiddle示例来显示输出。

function CalcWeekRange(data,begin,end){
    console.log(data,begin, end);
     newArr = data.filter(function(item){
        return (item.WeekNo >= begin && item.WeekNo <= end);
    });
    console.log(newArr); 

}

在此之后,我需要将结果总结为一个看起来像这样的对象:

    {
        "displayAd_imp": "140",
        "videoAd_imp": "290",
        "tv_imp": "530",
    }

最后一部分是我被困的地方:(

希望我提前明确提出问题!

1 个答案:

答案 0 :(得分:1)

您可以将reduce与初始累加器一起使用:

function weekRange(begin, end, data) {
  return data.filter(function(x) {
    return x.WeekNo >= begin && x.WeekNo <= end;
  }).reduce(function(acc, x) {
    Object.keys(acc).forEach(function(k) {
      acc[k] += Number(x[k]);
    });
    return acc;
  },{
    displayAd_imp: 0,
    videoAd_imp: 0,
    tv_imp: 0
  });
}