我有一个json字符串,如下所示
[{"_id":"9/17/2015","amt1":0,"amt2":13276.5},{"_id":"9/18/2015","amt1":8075,"amt2":6445.5}]
预期结果:
[{"_id": ["9/17/2015", "9/18/2015"], "amt1": [0, 8075], "amt2": [13276.5, 6445.5]}]
这是否可以在没有循环的情况下实现。由于json可能有超过500条记录..
可以帮助获得所需的输出..
答案 0 :(得分:2)
你去:
var data = [{"_id":"9/17/2015","amt1":0,"amt2":13276.5},{"_id":"9/18/2015","amt1":8075,"amt2":6445.5}];
var groupByKeys = function(data) {
var obj = {};
for(var i in data) {
var curr = data[i];
for(var key in curr) {
if(!obj[key]) obj[key] = [];
obj[key].push(curr[key]);
}
}
return obj;
}
document.write(JSON.stringify(groupByKeys(data)));