映射新的数组结构javascript
我有以下数组格式:映射新的数组结构javascript,javascript,arrays,map,underscore.js,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
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)
});
您也可以使用正常的for
循环,而不是forEach
,以获得更大的兼容性:
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)
});
唯一的区别是,这不会从源对象中删除
blah
属性。@jbabey-well不确定从何处开始:(非常需要一些帮助,非常感谢!我正在使用下划线,如果这有帮助的话:)否则,谢谢heapsOh,这就简化了问题。使用underline.js
,您只需执行以下操作:\uu.groupBy(myArr,'blah')
_.groupBy(myArr, 'blah');