我有JSON数据:
{"A1":"3","A2":"34","B1":"23","B2":"23","C1":"234","C2":"43",...}
我想分组或重组它
var dataJson1 = {
"A":{"A1":"3","A2":34},
"B":{"B1":"23","B2":"23"},
...
}
和
var dataJson2 = {
"0":{"A1":"3", "B1":"23", ...},
"1":{"A2":"34", "B2":"23", ...}
}
如何对json数据进行分组?
答案 0 :(得分:0)
只需迭代输入对象并构建其他对象:
var all = {
"A1": "3",
"A2": "34",
"B1": "23",
"B2": "23",
"C1": "234",
"C2": "43"
};
var dataJson1 = {};
var dataJson2 = {};
for (var k in all) {
// data json 1
var c = dataJson1[k[0]] = dataJson1[k[0]] || {};
c[k] = all[k];
// data json 2
c = dataJson2[k[1] - 1] = dataJson2[k[1] - 1] || {};
c[k] = all[k];
}
alert("JSON1: " + JSON.stringify(dataJson1));
alert("JSON2: " + JSON.stringify(dataJson2));