In JavaScript, you can use various methods to get all the properties of an object, including Object.keys()
, for...in
loop, and Object.getOwnPropertyNames()
.
Object.keys(obj);
Object.keys()
returns an array of strings containing the names of the object’s own enumerable properties.
for (const prop in obj) {
// Do something with `prop`
}
for...in
loop iterates over all properties of an object, including inherited properties.
Object.getOwnPropertyNames(obj);
Object.getOwnPropertyNames()
returns an array of strings containing the names of all the object’s own properties, including non-enumerable properties.
Get all properties of an object JavaScript example
Simple example code using each of the methods mentioned to retrieve the properties of an object:
const person = {
firstName: "John",
lastName: "Doe",
age: 30
};
// Object.keys()
const keys = Object.keys(person);
console.log(keys);
// for...in loop
for (const prop in person) {
console.log(prop);
}
// Object.getOwnPropertyNames()
const propertyNames = Object.getOwnPropertyNames(person);
console.log(propertyNames);
Output:
Here’s a summarizes the differences between Object.keys()
, for...in
loop, and Object.getOwnPropertyNames()
:
Method | Purpose | Retrieves | Inherits from prototype? |
---|---|---|---|
Object.keys() | Retrieve the names of an object’s own enumerable properties | Object’s own enumerable properties | No |
for...in loop | Iterate over all properties of an object, including inherited properties | All properties (including inherited ones) | Yes |
Object.getOwnPropertyNames() | Retrieve the names of all the object’s own properties, including non-enumerable properties | All properties (including non-enumerable ones) | No |
Comment if you have any doubts or suggestions on this JS Object property topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version