0

我有以下数组格式:

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"
            }
    }
    ]
}]
4

1 回答 1

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从源对象中删除该属性。

于 2013-01-28T14:15:04.937 回答