Javascript数组转换

时间:2013-04-25 17:07:35

标签: javascript jquery arrays

我想知道如何才能解决这个问题:

var data = [  
     {id:1,option1:'short',option2:'red',option3:'gold'},  
     {id:2,option1:'short',option2:'red',option3:'silver'},   
     {id:3,option1:'short',option2:'blue',option3:'gold'},  
     {id:4,option1:'short',option2:'blue',option3:'silver'},  
     {id:5,option1:'long',option2:'red',option3:'gold'},  
     {id:6,option1:'long',option2:'red',option3:'silver'},   
     {id:7,option1:'long',option2:'blue',option3:'gold'},  
     {id:8,option1:'long',option2:'blue',option3:'silver'}]

使用Jquery进行格式化的事情。

var new_data = {
            short:{
              red:{gold:1,silver:2},
              blue:{gold:3,silver:4}
            },
            long:{
              red:{gold:5,silver:6},
              blue:{gold:7,silver:8}
               }
       }

3 个答案:

答案 0 :(得分:4)

这比你想象的要容易。试试这个:

function helper(obj,tree,value) {
    for( var i=0, l=tree.length; i<l-1; i++) {
        obj[tree[i]] = obj[tree[i]] || {};
        obj = obj[tree[i]];
    }
    obj[tree[i]] = value;
}
var new_data = {}, l = data.length, i;
for( i=0; i<l; i++) {
    helper(new_data,[data[i].option1,data[i].option2,data[i].option3],data[i].id);
}

答案 1 :(得分:1)

这个普通的JS会这样做:

var data = […];
var new_data = {};
for (var i=0; i<data.length; i++) {
    var o = new_data;
    for (var j=1; j<3; j++) {
        var prop = data[i]["option"+j];
        o = o[prop] || (o[prop] = {});
    }
    o[data[i]["option"+j]] = data[i].id;
}

但是首先使用嵌套模式看起来更容易吗?

答案 2 :(得分:1)

您可以像这样使用.reduce()

var new_data = data.reduce(function(res, obj) {
    if (!res[obj.option1])
        res[obj.option1] = {};
    if (!res[obj.option1][obj.option2])
        res[obj.option1][obj.option2] = {};

    res[obj.option1][obj.option2][obj.option3] = obj.id;
    return res;
}, {});

或者像这样:

var new_data = data.reduce(function(res, obj) {
    var o = res;
    for (var i = 1; i < 3; i++)
        o = (o[obj["option" + i]] = o[obj["option" + i]] || {});

    o[obj.option3] = obj.id;
    return res;
}, {});