JavaScriptObjects and classes
Object. keys()
Returns an array of an object’s own, enumerable property names.
- Returns
- An array of strings with the property names.
- Changes the original
- No
Example
#JavaScript
const user = { name: 'Emma', level: 7, premium: true }
console.log(Object.keys(user))
console.log(Object.keys(user).length)
console.log(Object.keys({}).length === 0)Console
['name', 'level', 'premium']
3
true
Definition and usage
#The Object.keys() method takes an object and returns an array of strings with its property names. It only counts own (not inherited) and enumerable properties.
This lets you walk over an object with array methods: count its fields, check whether an object is empty, or build a list of options from a configuration’s keys.
The order of the keys is predictable: integer-like keys come first, in ascending order, followed by the remaining strings in the order they were added.
Syntax
#Syntax
Object.keys(obj)Parameters
#obj
object
The object whose keys you want to get.
More examples
#JavaScript
const ranking = { 10: 'Jack', 2: 'Mia', b: 'x', a: 'y' }
console.log(Object.keys(ranking))Console
['2', '10', 'b', 'a']
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- You can check for an empty object with
Object.keys(obj).length === 0. - If you need both the keys and the values at once, use
Object.entries().
Related entries
#- Object.values()Returns an array of an object’s own, enumerable property values.
- Object.entries()Returns an array of an object’s [key, value] pairs.
- for...inWalks the names of an object’s enumerable properties, including ones inherited from the prototype.
- Object.hasOwn()Checks whether an object has its own property with the given name.
Spotted a mistake or missing an example? Write to us.