Convert an Object to an Array in JavaScript
In this post, we will see how to convert an object to an array in JavaScript. To achieve this we can use below three methods.
Object.keys()
Object.values()
Object.entries()
Let’s go through with the below Object
var obj1 = { Name: 'Smith', City: 'New York'};
Advertisements
So long ago, in the ancient time if need to convert an object into an array, we have do something like below.
var keys = []; var values = []; for (var key in obj1) { keys.push(key); values.push(obj1[key]); } console.log(keys); //['Name', 'City'] console.log(values);//['Smith', 'New York']
ES6 – Object.keys
And then ES6 enters into the JS world. Now, there was a built-in method that quickly turns all the keys in my object into an array.
var keys = []; keys = Object.keys(obj1); console.log(keys); //['Name', 'City']
In ES6, we can only extract the keys. But I want my values too! And then ES2017 rolled inβ¦
Advertisements
ES2017 – Object.values
Now we can easily extract the values into the entries.
var values = []; values = Object.keys(obj1); console.log(values); //['Smith', 'New York']
Object.entries
ES2017, it gave us more. Now its grant us to extract the each entries.
var objArr = []; objArr = Object.entries(obj1); console.log(objArr); // [ ['Name', 'Smith'] , ['City', 'New York'] ];
Browser Support
Object.values
andObject.entries
, unfortunately, don’t support Internet ExplorerObject.keys
has the best support. Which means it supports Internet Explorer
1 Comment »