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 any of the 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. See the following example:

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 an object as an input parameter and returns an array which contains each value of the 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' ] ]

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts

Leave a Comment