Get an Object's Keys as Array in JavaScript

avatar

Borislav Hadzhiev

Sun Oct 10 20211 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 the array's indexes as strings.
index.js
const arr = ['one', 'two', 'three']; const keys = Object.keys(arr); // ๐Ÿ‘‡๏ธ ['0', '1', '2'] console.log(keys);

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee