Get an Object's Keys as Array in JavaScript

avatar

Borislav Hadzhiev

Sun Oct 10 20212 min read

Get an Object's Keys as Array in JavaScript #

To get the keys of an object as an array, use the Object.keys() method, passing it the object as a parameter. The method returns an array containing the object's property names in the same order as provided by a for ... in loop.

index.js
const obj = {id: 1, country: 'Chile', city: 'Santiago'}; const keys = Object.keys(obj); // 👇️ ['id', 'country', 'city'] console.log(keys);

The only parameter the Object.keys method takes is the object of which to get the property names.

The Object.keys method is supported in Internet Explorer versions 9-11. If you need to support older browsers use a for...in loop instead.
index.js
const obj = {id: 1, country: 'Chile', city: 'Santiago'}; const keys = []; for (const key in obj) { keys.push(key); } // 👇️ ['id', 'country', 'city'] console.log(keys);

In the code snippet we use the for...in loop to iterate over all of the object's keys. On each iteration we push the key into the keys array to achieve the same result as with the Object.keys method.

You can also pass an array to the Object.keys method. If you call theObject.keys method with an array, you would get the array's indexes as strings.
index.js
const arr = ['one', 'two', 'three']; const keys = Object.keys(arr); // 👇️ ['0', '1', '2'] console.log(keys);

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.