Skip to content

Get all properties of an object JavaScript

  • by

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:

Get all properties of an object JavaScript

Here’s a summarizes the differences between Object.keys(), for...in loop, and Object.getOwnPropertyNames():

MethodPurposeRetrievesInherits from prototype?
Object.keys()Retrieve the names of an object’s own enumerable propertiesObject’s own enumerable propertiesNo
for...in loopIterate over all properties of an object, including inherited propertiesAll properties (including inherited ones)Yes
Object.getOwnPropertyNames()Retrieve the names of all the object’s own properties, including non-enumerable propertiesAll 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

Leave a Reply

Your email address will not be published. Required fields are marked *