Borislav Hadzhiev
Sun Oct 10 2021·2 min read
Photo by Christopher Machicoane
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.
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.
Object.keys
method is supported in Internet Explorer versions 9-11. If you need to support older browsers use a for...in
loop instead.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.
Object.keys
method. If you call theObject.keys
method with an array, you would get the array's indexes as strings.const arr = ['one', 'two', 'three']; const keys = Object.keys(arr); // 👇️ ['0', '1', '2'] console.log(keys);