如何仅将对象数组(键值对)转换为嵌套数组

时间:2016-11-17 05:05:40

标签: javascript angularjs arrays json object

这就是我现在所拥有的。

[
    [
        {"label":"Year","type":"number"},
        {"label":"Value","type":"number"},
    ],
    {"2013" : 70}, 
    {"2014" : 78}, 
    {"2015" : 125}, 
    {"2016" : 153}
]

这是我用来生成上述代码的内容。

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'
}]);

我希望将它们组织成[Year, Value]对而不是对象,如下所示:

[["Year", "Value"], ["2013", 70], ["2014", 78], ["2015", 125], ["2016", 153]]

1 个答案:

答案 0 :(得分:0)

您正在将对象({})推入阵列。你想要的是在下面的第二行中使用数组括号([]):

for (var year in sum) {
  var tmp = [];
  tmp[year] = sum[year];
  result.push(tmp);
}