Javascript 如何在对象数组上使用 jQuery.map() 返回数组数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4875649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use jQuery.map() on array of objects to return array of arrays
提问by IgalSt
I would like to use jQuery to convert an array of objects to array of arrays using map.
我想使用 jQuery 将对象数组转换为使用 map 的数组数组。
For example if I have this:
例如,如果我有这个:
var ObjArr = [{ a:1,b:2 },{ a:2,b:3 },{ a:3,b:4 }];
var ArrArr = $.map(ObjArr, function(n,i){
return [ n.a, n.b ];
});
So that the result would be:
所以结果是:
ArrArr = [[1,2],[2,3],[3,4]]
回答by user113716
With the jQuery.map()
(docs)and map()
(docs)methods you need to double wrap the return value:
使用jQuery.map()
(docs)和map()
(docs)方法,您需要双重包装返回值:
var ArrArr = $.map(ObjArr, function(n,i){
return [[ n.a, n.b ]];
});
...otherwise for some reason it concats the Array being returned. This way it concats the outer Array, and placing the content (the inner Array) at the next index.
...否则由于某种原因它会连接正在返回的数组。通过这种方式,它连接外部 Array,并将内容(内部 Array)放置在下一个索引处。