Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
177
rated 0 times [  181] [ 4]  / answers: 1 / hits: 48908  / 14 Years ago, wed, february 2, 2011, 12:00:00

I would like to use jQuery to convert an array of objects to array of arrays using 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]]

More From » jquery

 Answers
34

With the jQuery.map()(docs) and map()(docs) methods you need to double wrap the return value:



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.


[#93933] Tuesday, February 1, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
frederickmohamedw

Total Points: 21
Total Questions: 123
Total Answers: 105

Location: The Bahamas
Member since Tue, Apr 27, 2021
3 Years ago
frederickmohamedw questions
Wed, Sep 23, 20, 00:00, 4 Years ago
Sat, Jul 18, 20, 00:00, 4 Years ago
Sun, Apr 26, 20, 00:00, 4 Years ago
Sat, Jan 11, 20, 00:00, 4 Years ago
Fri, Dec 27, 19, 00:00, 4 Years ago
;