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.
- Using Object.keys() method
- Using Object.values() method
- Using Object.entries() method
- Using for...in loop
Convert Object to Array using Object.keys() Method
The Object.keys() method returns an array of a given object's enumerable property names.
- Object.keys(obj) takes an object obj as an argument and returns an array containing the keys of the object.
- The values of the object are included in the resulting array.
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.
- Object.values(obj) returns an array containing the values of the object.
- The keys of the object are included in the resulting array.
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.
- Object.entries(obj) returns an array of arrays, where each inner array is a [key, value] pair from the original object.
- This method is useful when you need both the keys and values of the object in the resulting array.
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.
- The for...in loop iterates over the properties of the object.
- The hasOwnProperty() method checks if the object has the specified property as its own property (not inherited).
- The push() method is used to add [key, value] pairs to the 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' ] ]