[英]How to convert array of objects (key-value pair) to nested arrays only
This is what I currently have. 这就是我目前所拥有的。
[
[
{"label":"Year","type":"number"},
{"label":"Value","type":"number"},
],
{"2013" : 70},
{"2014" : 78},
{"2015" : 125},
{"2016" : 153}
]
this is what I am using to generate the above code. 这就是我用来生成上面的代码的东西。
var data = [
{"Year":2013,"Product":"A","Value":0},
{"Year":2013,"Product":"B","Value":20},
{"Year":2013,"Product":"A","Value":50},
{"Year":2014,"Product":"D","Value":55},
{"Year":2014,"Product":"M","Value":23},
{"Year":2015,"Product":"D","Value":73},
{"Year":2015,"Product":"A","Value":52},
{"Year":2016,"Product":"B","Value":65},
{"Year":2016,"Product":"A","Value":88}
];
var sum = data.reduce(function(res, product) {
if (!(product.Year in res)) {
res[product.Year] = product.Value;
} else {
res[product.Year] += product.Value;
}
return res;
}, {});
var result = [];
for (var year in sum) {
var tmp = {};
tmp[year] = sum[year];
result.push(tmp);
}
result.splice(0, 0, [{
label: 'Year',
type: 'number'
}, {
label: 'Value',
type: 'number'
}]);
and I want to organize them into [Year, Value]
pairs instead of objects, like this: 而且我想将它们组织成
[Year, Value]
对,而不是像这样的对象:
[["Year", "Value"], ["2013", 70], ["2014", 78], ["2015", 125], ["2016", 153]]
You are pushing objects ( {}
) into the array. 您正在将对象(
{}
)推入数组。 What you want is to use the array brackets instead ( []
) in the second line shown below: 您想要的是在下面显示的第二行中使用数组括号(
[]
):
for (var year in sum) {
var tmp = [];
tmp[year] = sum[year];
result.push(tmp);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.