0

我有以下 JSON:

[{"state":"MN","value":10},{"state":"MN","value":10},{"state":"MN","value":10},{"state":"NY","value":8},{"state":"NY","value":8},{"state":"NY","value":8}]

是否有 JQuery/JS 或任何其他 HTML 兼容语言中的命令允许我将上述 JSON 转换为以下内容:

[{"state":"MN","value":[10,10,10]},{"state":"NY","value":[8,8,8]}]

谢谢!

4

2 回答 2

3

下面的循环将为您提供所需的输出,

演示

var data = [{"state":"MN","value":10},{"state":"MN","value":10},{"state":"MN","value":10},{"state":"NY","value":8},{"state":"NY","value":8},{"state":"NY","value":8}];

var tmp = {};
var t;
$.each (data, function (i, val) {
   if (tmp.hasOwnProperty(val.state)) {
      t = tmp[val.state];
      t.push(val.value);
   } else {
      tmp[val.state] = [val.value];
   }   
});

var output = [];
for (i in tmp) {
    output.push({'state': i, 'value': tmp[i]});   
}

证明:

在此处输入图像描述

于 2012-04-19T21:37:17.893 回答
3

您可以使用:

var input=[{"state":"MN","value":10},{"state":"MN","value":10},{"state":"MN","value":10},{"state":"NY","value":8},{"state":"NY","value":8},{"state":"NY","value":8}]

var tmp={}, output=[];
while(o=input.pop()) (tmp[o.state] || (tmp[o.state]=[])).push(o.value); //you could even stop here if it is enough for you
for(k in tmp) output.push({state:k,value:tmp[k]});
于 2012-04-19T21:38:50.750 回答