![]() |
VOOZH | about |
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.
Table of Content
The Object.keys() method returns an array of a given object's enumerable property names.
[ 'company', 'contact', 'city' ]
The Object.values() method returns an array of a given object's own enumerable property values.
[ 'GeeksforGeeks', '+91-9876543210', 'Noida' ]
The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs.
[ [ 'company', 'GeeksforGeeks' ], [ 'contact', '+91-9876543210' ], [ 'city', 'Noida' ] ]
You can also use a for...in loop to iterate over the object's properties and construct an array.
[ [ 'company', 'GeeksforGeeks' ], [ 'contact', '+91-9876543210' ], [ 'city', 'Noida' ] ]
Another approach to convert an object to an array in JavaScript is by using the Array.from() method along with Object.entries(). This method creates a new, shallow-copied array instance from an array-like or iterable object. By combining Array.from() with Object.entries(), we can efficiently convert an object into an array of key-value pairs.
Example: The following example demonstrates how to use Array.from() to convert an object to an array.
[ [ 'name', 'Alice' ], [ 'age', 30 ], [ 'profession', 'Engineer' ] ]
map() MethodIn this approach, you can use the Object.keys() method to retrieve the keys of the object and then use the map() method to construct an array based on these keys. This is useful when you want to transform the object into a specific format, such as an array of objects where each object contains a key-value pair.
Example:
This example demonstrates how to use Object.keys() and map() to convert an object into an array of objects, where each object contains a key and value property.
[
{ key: 'name', value: 'Alice' },
{ key: 'age', value: 30 },
{ key: 'profession', value: 'Engineer' }
]