我有以下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]}]
谢谢!
答案 0 :(得分: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]});
}
<强>证明:强>
答案 1 :(得分: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]});