Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jQuery.map() on array of objects to return array of arrays

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]] 
like image 927
IgalSt Avatar asked Feb 02 '11 14:02

IgalSt


People also ask

Can I use map on an array of objects?

map() can be used to iterate through objects in an array and, in a similar fashion to traditional arrays, modify the content of each individual object and return a new array.

Does map return an array?

The map() method returns an entirely new array with transformed elements and the same amount of data. In the case of forEach() , even if it returns undefined , it will mutate the original array with the callback .

How do you map data from an array of objects in JavaScript?

The syntax for the map() method is as follows: arr. map(function(element, index, array){ }, this); The callback function() is called on each array element, and the map() method always passes the current element , the index of the current element, and the whole array object to it.


1 Answers

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.

like image 100
user113716 Avatar answered Sep 21 '22 04:09

user113716