![]() |
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 Convert Object to Array using Object.keys() MethodThe Object.keys() method returns an array of a given object’s enumerable property names.
Output [ 'company', 'contact', 'city' ] Convert Object to Array using Object.values() MethodThe Object.values() method returns an array of a given object’s own enumerable property values.
Output [ 'GeeksforGeeks', '+91-9876543210', 'Noida' ] Convert Object to Array using Object.entries() MethodThe Object.entries() method returns an array of a given object’s own enumerable string-keyed property [key, value] pairs.
Output [ [ 'company', 'GeeksforGeeks' ], [ 'contact', '+91-9876543210' ], [ 'city', 'Noida' ] ] Convert Object to Array using for…in LoopYou can also use a for…in loop to iterate over the object’s properties and construct an array.
Output [ [ 'company', 'GeeksforGeeks' ], [ 'contact', '+91-9876543210' ], [ 'city', 'Noida' ] ] Using Array.from() MethodAnother 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.
Output [ [ 'name', 'Alice' ], [ 'age', 30 ], [ 'profession', 'Engineer' ] ] |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 11 |