Q:

Javascript: How to group JSON Object to array

I have JSON data:
{"A1":"3","A2":"34","B1":"23","B2":"16","C1":"234","C2":"43","D1":"234","D2":"54"}

Now I just want group JSON data into an array:
var arr1 = [
 {"A":{"val1"=>"3", "val2"=>"34"}},   //val1 = A1, val2 = A2
 {"B":{"val1"=>"23", "val2" =>"16"}}, //val1 = B1, val2 = B2
 ...
]

AND
var arr2 = [
 "0":{"A1":"3", "B1":"23", ...}, 
 "1":{"A2":"34", "B2":"16", ...}
]

How can I group and create the array? Help me, Thanks.

A:

there we go
var a = {"A1":"3","A2":"34","B1":"23","B2":"16","C1":"234","C2":"43","D1":"234","D2":"54"};

var arr1Obj = {};
var arr2 = [{"0": {}}, {"1": {}}];
for (var key in a) {
    var split = (key.split(""));
    if (!arr1Obj[split[0]]) {
        arr1Obj[split[0]] = {}
    }
    arr1Obj[split[0]]["val" + split[1]] = a[key];

    arr2[parseInt(split[1]) - 1][key] = a[key];
}
var arr1 = [];
for (var key in arr1Obj) {
    var obj = {};
    obj[key] = arr1Obj[key];
    arr1.push(obj);
}

you can try it here (end of answer):

run = function() {
    var input = document.getElementById("input");
    var a = JSON.parse(input.value);
    
    var arr1Obj = {};
    var arr2 = [{"0": {}}, {"1": {}}];
    for (var key in a) {
        var split = (key.split(""));
        if (!arr1Obj[split[0]]) {
            arr1Obj[split[0]] = {}
        }
        arr1Obj[split[0]]["val" + split[1]] = a[key];
        
        arr2[parseInt(split[1]) - 1][key] = a[key];
    }
    var arr1 = [];
    for (var key in arr1Obj) {
        var obj = {};
        obj[key] = arr1Obj[key];
        arr1.push(obj);
    }
    
    document.getElementById("output1").innerHTML = JSON.stringify(arr1);
    document.getElementById("output2").innerHTML = JSON.stringify(arr2);
}
input {
    width: 100%;
}

div {
    margin-top: 10px;
}
<input type="text" id="input"  value='{"A1":"3","A2":"34","B1":"23","B2":"16","C1":"234","C2":"43","D1":"234","D2":"54"}' />

<button onclick="run()">run</button>

<div id="output1"></div>
<div id="output2"></div>

