How to Convert Object to Array in JavaScript
-
Use
Object.keys()
andmap()
to Convert an Object to an Array in JavaScript -
Use
Object.entries()
to Convert an Object to an Array in JavaScript
Objects are non-primitive data types forming the building blocks of modern JavaScript. Unlike primitive data types that are singular, objects can constitute several primitive data types in a complex fashion.
An array is a single variable used to store a list of elements. This tutorial explains how to convert an object to an array of key-value pairs in JavaScript.
Use Object.keys()
and map()
to Convert an Object to an Array in JavaScript
The Object.keys()
method helps retrieve all the enumerable properties in an object into an array of strings. It takes the object obj
as an argument, and we can add a callback function to get the desired result.
To convert an object to an array we first call the Object.keys()
method on the object, and then we call the map()
function on its output to map the key and value of the object in the corresponding array. It will contain the properties in the same order as the object.
var obj = {'2': 3, '1': 37, '23': 40, '41': 220, '115': 230};
var arr = Object.keys(obj).map(function(key) {
return [Number(key), obj[key]];
});
console.log(arr);
Output:
[[1, 37], [2, 3], [23, 40], [41, 220], [115, 230]]
Use Object.entries()
to Convert an Object to an Array in JavaScript
The Object.entries()
method works similar to the Object.keys()
method, and you can also use it to convert an object to an array. But it returned only the keys, and we had to use the map()
function to recreate the enumerable object properties in the array.
Object.entries()
simplifies the task by directly returning the answer in an array. Like Object.keys()
, the properties are returned in the same order as the object.
var obj = {'2': 3, '1': 37, '23': 40, '41': 220, '115': 230};
var arr = Object.entries(obj);
console.log(arr);
Output:
[
[ '1', 37 ],
[ '2', 3 ],
[ '23', 40 ],
[ '41', 220 ],
[ '115', 230 ]
]
Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.
LinkedInRelated Article - JavaScript Object
- How to Search Objects From an Array in JavaScript
- How to Get the Object's Value by a Reference to the Key
- How to Find Object in Array by Property Value in JavaScript
- How to Print Objects in JavaScript
- How to Destroy Object in JavaScript
- Nested Objects in JavaScriptn
Related Article - JavaScript Array
- How to Check if Array Contains Value in JavaScript
- How to Create Array of Specific Length in JavaScript
- How to Convert Array to String in JavaScript
- How to Remove First Element From an Array in JavaScript
- How to Search Objects From an Array in JavaScript
- How to Convert Arguments to an Array in JavaScript