我有这个JSON
[ {"key":"main1","value":320}, {"key":"main2","value":240}, {"key":"front1","value":220}, {"key":"main1","value":300}, {"key":"main2","value":240}, {"key":"front1","value":120}, {"key":"front5","value":120} ]
需要像这样进行转换,当它们具有相同的键并从相同的值创建数组时将其关闭。
[ {"main1": [320, 300]}, {"main2": [240, 240]}, {"front1": [220, 120]}, {"front5": [120]} ]
答案 0 :(得分:2)
你可以这样做:
var element,
result = {},
test = [
{"key":"main1","value":320},
{"key":"main2","value":240},
{"key":"front1","value":220},
{"key":"main1","value":300},
{"key":"main2","value":240},
{"key":"front1","value":120},
{"key":"front5","value":120}
];
for (i in test) {
element = test[i];
if (!result[element.key]) {
result[element.key]=[element.value];
} else {
result[element.key].push(element.value);
}
}
演示 - >的 http://jsfiddle.net/e8afaak8/ 强>