JavaScript Object.keys() method is used to return an array of a given object’s own enumerable property names.
This method is commonly used for iterating over an object’s properties.
Syntax
Object.keys(obj)
Parameters
obj(required): An iterable object.
Return Value
It returns an array of strings representing all the enumerable properties of the given object.
Visual Represenatation
Example 1: How to Use Object.keys() Method
let obj = {
name: 'Krunal',
education: 'IT Engineer',
country : 'India'
} ;
console.log(Object.keys(obj));
Output
[ 'name', 'education', 'country' ]
So, in the above example, we get an array of object keys.
We can do the same with an array. We can get the array keys as well.
//array
let arr = [
'apple',
'microsoft',
'amazon',
'alphabet',
'tencent',
];
console.log(Object.keys(arr));
Output
[ '0', '1', '2', '3', '4' ]
Example 2: Use array-like objects
let object = { 0: "Lion", 1: "Tiger", 2: "Deer" };
console.log(Object.keys(object));
//random key ordering
let object1 = {1: "Tiger", 0: "Lion", 2: "Deer" };
console.log(Object.keys(object1));
Output
[ '0', '1', '2' ]
[ '0', '1', '2' ]
Example 3: Pass the non-enumerable property
An example of a function property of an object is the Non-enumerable property. Therefore, we will not get the keys to that property.
let myObj = Object.create({}, {
getName: {
value: function () { return this.name; }
}
});
myObj.name = 'krunal';
console.log(Object.keys(myObj));
Output
[ 'name' ]
Browser Compatibility
- Chrome 5 and above
- Edge 12 and above
- Firefox 4 and above
- Opera 12 and above
- Safari 5 and above