Open In App

How to Convert Object to Array in JavaScript?

In this article, we will learn how to convert an Object to an Array in JavaScript. Given an object, the task is to convert an object to an Array in JavaScript. Objects and Arrays are two fundamental data structures. Sometimes, it's necessary to convert an object to an array for various reasons, such as easier iteration or compatibility with certain functions that expect arrays.

Below are the following approaches to converting Objects to Arrays in JavaScript.

Convert Object to Array using Object.keys() Method

The Object.keys() method returns an array of a given object's enumerable property names.

const obj = {
    company: 'GeeksforGeeks',
    contact: '+91-9876543210',
    city: 'Noida'
};

const keysArray = Object.keys(obj);
console.log(keysArray);

Output
[ 'company', 'contact', 'city' ]

Convert Object to Array using Object.values() Method

The Object.values() method returns an array of a given object's own enumerable property values.

const obj = {
    company: 'GeeksforGeeks',
    contact: '+91-9876543210',
    city: 'Noida'
};

const valuesArray = Object.values(obj);
console.log(valuesArray); 

Output
[ 'GeeksforGeeks', '+91-9876543210', 'Noida' ]

Convert Object to Array using Object.entries() Method

The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs.

const obj = {
    company: 'GeeksforGeeks',
    contact: '+91-9876543210',
    city: 'Noida'
};

const entriesArray = Object.entries(obj);
console.log(entriesArray);

Output
[
  [ 'company', 'GeeksforGeeks' ],
  [ 'contact', '+91-9876543210' ],
  [ 'city', 'Noida' ]
]

Convert Object to Array using for...in Loop

You can also use a for...in loop to iterate over the object's properties and construct an array.

const obj = {
    company: 'GeeksforGeeks',
    contact: '+91-9876543210',
    city: 'Noida'
};

const arrayFromObj = [];

for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
        arrayFromObj.push([key, obj[key]]);
    }
}

console.log(arrayFromObj);

Output
[
  [ 'company', 'GeeksforGeeks' ],
  [ 'contact', '+91-9876543210' ],
  [ 'city', 'Noida' ]
]
Article Tags :