Skip to content

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 and Object.entries, unfortunately, don’t support Internet Explorer
  • Object.keys has the best support. Which means it supports Internet Explorer

1 Comment »

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.