按值变化的不同长度的Sum对象数组

时间:2016-12-12 02:03:13

标签: javascript arrays

将不同长度的对象数组求和的最佳方法是:

data = [{"category":"category1","months":{"1":34,"2":67,"3":29,...}
{"category":"category2","months":{"1":34,"2":627,"3":292,...}
{"category":"category3","months":{"1":46,"2":665,"3":129,...}
{"category":"category4","months":{"1":624,"2":667,"3":629,...}
{"category":"category5","months":{"1":32,"2":637,"3":299,...}
}]

我希望基本上按月分组,并将其分配到总类别。所以我会得到一个新的对象,如下所示,我将推送到我的数据对象:

{"category":"total","months":{"1":770,"2":2663,"3":1378,...}

我最终会:

data = [{"category":"category1","months":{"1":34,"2":67,"3":29,...}
{"category":"category2","months":{"1":34,"2":627,"3":292,...}
{"category":"category3","months":{"1":46,"2":665,"3":129,...}
{"category":"category4","months":{"1":624,"2":667,"3":629,...}
{"category":"category5","months":{"1":32,"2":637,"3":299,...}
{"category":"total","months":{"1":770,"2":2663,"3":1378,...}
}]

2 个答案:

答案 0 :(得分:1)

使用Array.prototype.reducehash table获取总数'对象以及稍后将其推回到数据以获取所需的数据结构。

见下面的演示:



var data=[{"category":"category1","months":{"1":34,"2":67,"3":29}},{"category":"category2","months":{"1":34,"2":627,"3":292}},{"category":"category3","months":{"1":46,"2":665,"3":129}},{"category":"category4","months":{"1":624,"2":667,"3":629}},{"category":"category5","months":{"1":32,"2":637,"3":299}}]

var result = data.reduce(function(hash){
  return function(p,c){
    Object.keys(c.months).forEach(function(e){
      if(e in p.months) {
        p.months[e] += c.months[e];
      } else {
        p.months[e] = +c.months[e];
      }
    });
    return p;
  }
}(Object.create(null)), {category:"total",months:{}});

console.log(result);

// now push this to data
data.push(result);

// console.log(data);

.as-console-wrapper{top:0;max-height:100%!important;}




答案 1 :(得分:1)

sudo apt-get install ruby2.0 ruby2.0-dev
sudo apt-get install zlib1g-dev
sudo gem2.0 install jekyll