The Bndr The Bndr - 6 months ago 11
jQuery Question

Converting a JS object to an array

My application creates a JavaScript object, like the following:

myObj= {1:[Array-Data], 2:[Array-Data]}


But I need this object as an array.

array[1]:[Array-Data]
array[2]:[Array-Data]


So I tried to convert this object to an array by iterating with
$.each
through the object and adding the element to an array:

x=[]
$.each(myObj, function(i,n) {
x.push(n);});


Is there an better way to convert an object to an array or maybe a function?

Answer
var myObj = {
    1: [1, 2, 3],
    2: [4, 5, 6]
};

var array = $.map(myObj, function(value, index) {
    return [value];
});


console.log(array);

Output:

[[1, 2, 3], [4, 5, 6]]
Comments