How to Convert Object to an Array in JavaScript

In this tutorial, we will learn how to convert an object to an array in JavaScript.

As we know an object is a collection of comma-separated key-value pairs. So based on our requirement, we can use following three methods to convert an object into an array:

  1. Using Object.keys()
  2. Using Object.values()
  3. Using Object.entries()

Let’s discuss each method one by one.


1. Using Object.keys() Method

The method Object.keys() takes object as an input parameter and returns an array of keys. Refer the example below.

Example:

// Convert object to array using Object.keys() method
let obj = {
        'name': 'John',
        'age': 23,
        'gender': 'Male'
}

keys_array = Object.keys(obj)
console.log(keys_array)

Output:

[ 'name', 'age', 'gender' ]

2. Using Object.values() Method

Object.values() also takes object as an input parameter and returns an array which contains each value of given object.

Example:

// Convert object to array using Object.values() method
let obj = {
  'name': 'John',
  'age': 23,
  'gender': 'Male'
}

values_array = Object.values(obj)
console.log(values_array)

Output:

[ 'John', 23, 'Male' ]

3. Using Object.entries() Method

The Object.entries() returns a 2-D array. This 2-D array contains array of each key-value pair.

Example:

// Convert object to array using Object.entries() method
let obj = {
  'name': 'John',
  'age': 23,
  'gender': 'Male'
}

key_value_array = Object.entries(obj)
console.log(key_value_array)

Output:

[ [ 'name', 'John' ], [ 'age', 23 ], [ 'gender', 'Male' ] ]