Skip to content

JavaScript get object property name

In JavaScript, you can use the Object.keys() method to get an array of the property names of an object. This method returns an array containing the names of all enumerable properties of the object. You can then use this array to access and manipulate the object’s properties as needed.

Object.keys(object)

JavaScript gets object property name example

A simple example code gets the property names of an object myObject and log them to the console.

const myObject = {
  name: 'John',
  age: 30,
  address: '123 Main St'
};

const propertyNames = Object.keys(myObject);

console.log(propertyNames);

Output:

JavaScript get object property name

Another example

const myObject = {
  name: 'John',
  age: 30,
  address: '123 Main St'
};

const propertyNames = Object.keys(myObject);

propertyNames.forEach(function(propertyName) {
  console.log(propertyName + ': ' + myObject[propertyName]);
});

Output:

name: John
age: 30
address: 123 Main St

For each property name, we use the bracket notation (myObject[propertyName]) to access the corresponding value of the property and log it to the console along with the property name. This allows us to perform some action based on each property of the object.

Comment if you have any doubts or suggestions on this JS object 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 *