得到这个数组:
var arr = [
{
series: [
{
"name": 2014,
"data": [19, 17, 15, 12, 10, 10, 12, 10, 11, 14, 14, 18]
},
{
"name": 2015,
"data": [18, 17, 16, 12, 10, 7, 6, 8, 8, 11, 15, 30]
},
]
},
{
series: [
{
"name": 2014,
"data": [32, 17, 15, 12, 33 10, 33, 10, 11, 14, 14, 18]
},
{
"name": 2015,
"data": [45, 10, 12, 55, 77, 7, 6, 8, 8, 11, 33, 30]
},
]
},
]
我需要创建一个返回汇总系列的函数:
var series = [
{
year: '2014',
data: [51, 34....],
},
{
year: '2015',
data: [63, 27....],
}
]
我可以循环来执行此操作,但我想有一些聪明的方法可以使用下划线?可能具有reduce
功能。有关如何做到这一点的任何想法?
答案 0 :(得分:1)
another_df
答案 1 :(得分:0)
您可以使用一些迭代和一个对象作为分组年份的参考。
var arr = [{ series: [{ "name": 2014, "data": [19, 17, 15, 12, 10, 10, 12, 10, 11, 14, 14, 18] }, { "name": 2015, "data": [18, 17, 16, 12, 10, 7, 6, 8, 8, 11, 15, 30] }] }, { series: [{ "name": 2014, "data": [32, 17, 15, 12, 33, 10, 33, 10, 11, 14, 14, 18] }, { "name": 2015, "data": [45, 10, 12, 55, 77, 7, 6, 8, 8, 11, 33, 30] }] }],
series = [];
arr.forEach(function (a) {
Object.keys(a).forEach(function (k) {
a[k].forEach(function (b) {
if (!this[b.name]) {
this[b.name] = { year: b.name, data: [] };
series.push(this[b.name]);
}
b.data.forEach(function (c, i) {
this[b.name].data[i] = (this[b.name].data[i] || 0) + c;
}, this);
}, this);
}, this);
}, {});
document.write('<pre>' + JSON.stringify(series, 0, 4) + '</pre>');