简体   繁体   中英

How to group JSON data using Javascript/jquery?

I have JSON data:

{"A1":"3","A2":"34","B1":"23","B2":"23","C1":"234","C2":"43",...}

I would like to group, or restructure it like so

var dataJson1 = {
 "A":{"A1":"3","A2":34}, 
 "B":{"B1":"23","B2":"23"}, 
 ...
}

AND

var dataJson2 = {
 "0":{"A1":"3", "B1":"23", ...}, 
 "1":{"A2":"34", "B2":"23", ...}
}

How can I group json data?

Just iterate your input object and build the other objects:

 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)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM