The Object.getOwnPropertyNames() method can retrieve the property names of an object.
Object.getOwnPropertyNames(object) |
This example retrieves all properties of an object:
// Create an Object const person = { firstName: “John”, lastName : “Doe”, language : “EN” }; // Get all Properties Object.getOwnPropertyNames(person); |
Object.getOwnPropertyNames() will also include properties that are non-enumerable.
// Create an Object const person = { firstName: “John”, lastName : “Doe”, language : “EN” }; // Set the language Property not enumerable Object.defineProperty(person, “language”, {enumerable:false}); // Get all Properties Object.getOwnPropertyNames(person); |
The Object.keys() method can
Object.keys(object) |
This example uses Object.keys() instead of Object.getOwnPropertyNames().
// Create an Object const person = { firstName: “John”, lastName : “Doe”, language : “EN” }; // Change the “language” Property Object.defineProperty(person, “language”, {enumerable:false}); // Get all Enumerable Properties Object.keys(person); |
Note: The getOwnPropertyNames() method returns all properties, while the Object.keys() method returns only enumerable properties. If object properties are defined with enumerable: false , both methods will return the same result. |
The Object.defineProperty() method can also be used to define getters and setters.
//Create an object const person = {firstName:“John”, lastName:“Doe”}; // Define a getter Object.defineProperty(person, “fullName”, { get: function () {return this.firstName + ” “ + this.lastName;} }); |
// Define object const obj = {counter:0}; // Define setters Object.defineProperty(obj, “reset”, { get : function () {this.counter = 0;} }); Object.defineProperty(obj, “increment”, { get : function () {this.counter++;} }); Object.defineProperty(obj, “decrement”, { get : function () {this.counter–;} }); Object.defineProperty(obj, “add”, { set : function (value) {this.counter += value;} }); Object.defineProperty(obj, “subtract”, { set : function (i) {this.counter -= i;} }); // Play with the counter: obj.reset; obj.add = 5; obj.subtract = 1; obj.increment; obj.decrement; |
JavaScript objects inherit properties from their prototype.
The delete keyword does not remove inherited properties, but if a property is deleted from the prototype, it will affect all objects that inherit from that prototype.