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?
The solving is very simple
You can create a simple function to do the conversion from
object
toarray
, something like this can do the job for you using pure javascript:or this one:
and call and use the function as below:
Also in the future we will have something called
Object.values(obj)
, similar toObject.keys(obj)
which will return all properties for you as an array, but not supported in many browsers yet...Simply do
That's all!
If you are looking for a functional approach:
Results in:
The same with an ES6 arrow function:
With ES7 you will be able to use
Object.values
instead (more information):Or if you are already using Underscore/Lo-Dash:
ECMASCRIPT 5:
ECMASCRIPT 2015 or ES6: