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?
If you want to keep the name of the object's properties as values. Example:
Use
Object.keys()
,Array.map()
andObject.assign()
:Result:
Explanation:
Object.keys()
enumerates all the properties of the source ;.map()
applies the=>
function to each property and returns an Array ;Object.assign()
merges name and value for each property.Fiddle Demo
Extension to answer of bjornd .
Reference
Array.prototype.slice()
Function.prototype.apply()
Object.prototype.hasOwnProperty()
Object.keys()
Output:
Since ES5 Object.keys() returns an array containing the properties defined directly on an object (excluding properties defined in the prototype chain):
ES6 takes it one step further with arrow functions:
I made a custom function:
ES8 way made easy:
The official documentation