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

「何とか」の下の値が一緒になるように新しい配列をマップするにはどうすればよいのでしょうか。

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 に答える