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.
Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…
Let's understand about how to use coding to improve your website's SEO. In today’s computerized…
Let's understand the most important linux commands for web developers. Linux, as an open-source and…
Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…
Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…
Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…