JavaScript

How to convert object to array in JavaScript

Share your learning

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.

Satpal

Recent Posts

How to Switch PHP Versions in XAMPP Easily: Managing Multiple PHP Versions on Ubuntu

Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…

1 year ago

How to Use Coding to Improve Your Website’s SEO Ranking?

Let's understand about how to use coding to improve your website's SEO. In today’s computerized…

1 year ago

Most Important Linux Commands for Web Developers

Let's understand the most important linux commands for web developers. Linux, as an open-source and…

1 year ago

Top 75+ Laravel Interview Questions Asked by Top MNCs

Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…

1 year ago

Mailtrap Integration for Email Testing with Laravel 10

Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…

1 year ago

Firebase Cloud Messaging (FCM) with Ionic 6: Push Notifications

Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…

1 year ago