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]]
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With