映射新的数组结构javascript

时间:2013-01-28 14:10:01

标签: javascript arrays map underscore.js

我有以下数组格式:

var myArr = [
{
    "a": "1",
    "b": "2",
    "c": "3",
    "d" {
        "0" : "1",
        "1" : "2"
    },
    "blah" : "me"
},
{
    "a": "5",
    "b": "3",
    "c": "1",
    "d" {
        "0" : "6",
        "1" : "3"
    },
    "blah" : "me"
},
{
    "a": "5",
    "b": "3",
    "c": "1",
    "d" {
        "0" : "6",
        "1" : "3"
    },
    "blah" : "you"
}
]

我想知道如何映射一个新数组,使“blah”下的值像

一样
var myArr = [{
    "me" : [
    {
        "a": "1",
        "b": "2",
        "c": "3",
        "d": {
            "0" : "1",
            "1" : "2"
            }
    },
    {
        "a": "5",
        "b": "3",
        "c": "1",
        "d": {
            "0" : "6",
            "1" : "3"
            }
    }
    ],
    "you" : [
    {
        "a": "5",
        "b": "3",
        "c": "1",
        "d": {
            "0" : "6",
            "1" : "3"
            }
    }
    ]
}]

1 个答案:

答案 0 :(得分:1)

这很有可能,试试这个:

var output = {};
myArr.forEach(function(elem){     // Loop trough the elements in `myArr`
    if(!output[elem.blah]){       // If the output object doesn't have a property named by elem.blah, yet
        output[elem.blah] = [];   // Create a empty array
    }
    output[elem.blah].push(elem); // Push the current element to that array
    delete elem.blah;             // And delete the mention of `blah` from it (optional)
});

除了forEach之外,您还可以使用普通的for循环,以获得更高的兼容性:

var output = {};
for(var i = 0; i < myArr.length; i++){ // Loop trough the elements in `myArr`
    var elem = myArr[i];
    if(!output[elem.blah]){            // If the output object doesn't have a property named by elem.blah, yet
        output[elem.blah] = [];        // Create a empty array
    }
    output[elem.blah].push(elem);      // Push the current element to that array
    delete elem.blah;                  // And delete the mention of `blah` from it (optional)
});

使用underscore.js,您可以执行此操作:

_.groupBy(myArr, 'blah');

唯一的区别是,这不会从源对象中删除blah属性。