How to convert an object to an array in JavaScript

To convert an object to an array in JavaScript, you can use one of the following three methods: Object.keys(), Object.values(), and Object.entries().

The Object.keys() method was introduced in ES6 or ECMAScript 2015. Later in ECMAScript 2017 (ES8), two new methods, Object.entries() and Object.values(), were added to convert an object to an array.

Let us say you have got the following foods object:

const foods = {
    pizza: '🍕',
    burger: '🍔',
    fries: '🍟',
    cake: '🎂'
};

Object.keys() Method

The Object.keys() method returns an array of the given object's own enumerable property names. The order of the property names is the same as you get while iterating over the properties of the object manually.

Here is an example that converts property's names of the foods object to an array:

const keys = Object.keys(foods);

console.log(keys);
// [ 'pizza', 'burger', 'fries', 'cake' ]

Object.values() Method

The Object.values() method is similar to Object.keys() except that it returns an array of the given object's own enumerable property values:

const keys = Object.values(foods);

console.log(keys);
// [ '🍕', '🍔', '🍟', '🎂' ]

The order of the property's values is the same as that provided by the for..in loop.

Object.entries() Method

The Object.entries() method converts the own enumerable string-keyed property pairs of an object to an array:

const keys = Object.entries(foods);

console.log(keys);
// [
//     ['pizza', '🍕'],
//     ['burger', '🍔'],
//     ['fries', '🍟'],
//     ['cake', '🎂']
// ]

The order of the property's key-value pairs is similar to what for...in loop provides.

Browser compatibility

The Object.keys() method works in all modern browsers and IE9 and up. However, the Object.values() and Object.entries() methods are not supported by Internet Explorer and are only available to use in modern browsers.

Read Next: How to convert an array to an object in JavaScript

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.