Unique Array并将其设为JSON

时间:2014-07-08 16:40:33

标签: javascript jquery

我有一个这样的数组: myArray = {" a:10"," a:5"," a:25"," b:10",&#34 ; b:25" b:20"" C:5"" C:30"" C:15"}。如何使用javascript或jquery构建这样的json对象?

{"":[" 10"" 5"" 25&#34]," B" :" 10"" 25"" 20&#34]," C":[" 5",& #34; 30"" 15"]}

1 个答案:

答案 0 :(得分:1)

这个怎么样:

var myArray = ["a:10","a:5","a:25","b:10","b:25","b:20","c:5","c:30","c:15"],
    output = {};

for (var i = 0; i<myArray.length; i++){
    var item = myArray[i].split(":");
    var key = item[0];
    var value = item[1];
    var array = output[key];
    if (!array){
        array = [];
        output[key] = array
    }
    array.push(value);
}

或更实用的方式:

myArray.map(function(i){
        var parts = i.split(":");
        return {key:parts[0], value: parts[1]}
    })
    .reduce(function(p,c){
        var array = p[c.key];
        if (!array){
            array = [];
            p[c.key] = array
        }
        array.push(c.value);
        return p;
    },{});