What is Object.keys in JavaScript?
The Object.keys method will return an array that contains the property name of the object – the symbols and non-enumerable properties are not included. The order of the returned properties is the same as the order that occurs in the for...in loop.
Syntax
Object.keys(obj)
Example
let male = {gender : "male"};let user = Object.create(male);user.name = "Ram";user.age = 20;user.getName = function(){return this.name;}user[Symbol("symbol")] = "symbol";Object.defineProperty(user, "non-enumerable", {enumerable: false})console.log("The user object is ", user);console.log("\nKeys of the user object is ", Object.keys(user))// non-enumerable properties,symbols and inherited properties are not included in the keys
In the above code, we have:
- Created the
userobject frommaleobject. - Added
symbolas a property key touserobject . - Added a
non-enumerableproperty touserobjecct.
When we call the Object.keys method by passing the user object as an argument, we will get an array of its own object properties. It doesn’t include:
- Symbol
Inherited properties In our case, maleobject properties are inherited properties that are not included.Non-enumerable properties Properties that don’t occur in for…in loop
To get an object’s own enumerable and non-enumerable properties, we can use
Object.getOwnPropertyNames.