繁体   English   中英

映射新的数组结构javascript

[英]Mapping new array structure javascript

我有以下数组格式:

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

很有可能,请尝试以下操作:

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属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM