Javascript:如何将JSON对象分组到数组

时间:2014-11-16 15:42:50

标签: javascript jquery json group-by

我有JSON数据:

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

现在我只想将组JSON数据放入数组中:

var arr1 = [
 {"A":{"val1"=>"3", "val2"=>"34"}},   //val1 = A1, val2 = A2
 {"B":{"val1"=>"23", "val2" =>"16"}}, //val1 = B1, val2 = B2
 ...
]

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

如何分组和创建数组?帮帮我,谢谢。

1 个答案:

答案 0 :(得分:0)

我们去了

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

你可以在这里试试(答案结束):

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>