[英]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.