How to convert object to array in JavaScript
In JavaScript, most of the time we deal with the objects, but sometimes we may need an array like to create select box options with JavaScript loops.
Let’s assume we have an object called charges
.
const charges = {'0' : 234, '1' : 433, '2' : 900}
Now, if we use Object.keys()
, it will print the below output.
const charges = {'0' : 234, '1' : 433, '2' : 900} let arrCharges = Object.keys(charges); console.log( arrCharges );
Output:
[ '0', '1', '2' ]
Now, if we use Object.values()
, it will print the below output.
const charges = {'0' : 234, '1' : 433, '2' : 900} let arrCharges = Object.values(charges); console.log( arrCharges );
Output:
[ 234, 433, 900 ]
Now, if we use Object.entries()
, it will print the below output.
const charges = {'0' : 234, '1' : 433, '2' : 900} let arrCharges = Object.entries(charges); console.log( arrCharges );
Output:
[ [ '0', 234 ], [ '1', 433 ], [ '2', 900 ] ]
And yes we can use Object.fromEntries()
to convert array to object again, the output will be below.
const charges = {'0' : 234, '1' : 433, '2' : 900} let arrCharges = Object.entries(charges); console.log( Object.fromEntries(arrCharges) )
Output:
{ '0': 234, '1': 433, '2': 900 }
But, if we want to change the data type of key or the value then we can use the below approach. We are going to change the key’s data type in the example below.
const charges = {'0' : 234, '1' : 433, '2' : 900} let arr = Object.entries(charges).map(entry => [Number(entry[0]), entry[1]]) console.log(arr)
Output:
[ [ 0, 234 ], [ 1, 433 ], [ 2, 900 ] ]
Hope you found this article useful. Please share your suggestions or doubts in the comment section below.