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?
How about
jQuery.makeArray(obj)
This is how I did it in my app.
I think you can use
for in
but checking if the property is not inerithedEDIT - if you want you could also keep the indexes of your object, but you have to check if they are numeric (and you get undefined values for missing indexes:
If you know the maximum index in you object you can do the following:
Nowadays, there is a simple way to do this : Object.values().
Output:
This doesn't required jQuery, it's been defined in ECMAScript 2017.
It's supported by every modern browser (forget IE).
The best method would be using a javascript -only function:
After some tests, here is a general object to array function convertor:
You have the object:
The function:
Function Use:
You Get:
So then you can reach all keys & values like:
Result in console:
Edit:
Or in prototype form:
And then use like: