W3docs

How to List the Properties of a JavaScript Object

Read this tutorial and learn useful information about the two popular built-in methods that are used for listing the properties of the object in JavaScript.

In this tutorial, two most used methods are presented, which will list the properties of a JavaScript object.

You can use the built-in <kbd class="highlighted">Object.keys</kbd> method which is supported in the modern browsers:

Javascript Object.keys method

let keys = Object.keys(myObj);

Example:

Javascript Object.keys method

javascript— editable

To retrieve the list of the property names, you can do the following:

Javascript object list of the property names

let getKeys = function (obj) {
  let keysArr = [];
  for (var key in obj) {
    keysArr.push(key);
  }
  return keysArr;
}

Example:

Javascript object list of the property names

javascript— editable

Alternatively, you can attach a custom method to the prototype to allow calling it on any object. However, extending the prototype has side effects and is not recommended.

You can also use the for...in construct to iterate over an object for its attribute names. However, doing so, you will iterate over all attribute names in the object's prototype chain. To iterate only over the attributes of the object, you can use the <kbd class="highlighted">hasOwnProperty()</kbd> method like this:

Javascript object hasOwnProperty() method

for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    /* code here */
  }
}

Example:

Javascript object hasOwnProperty() method

javascript— editable

The Object.keys() method

The <kbd class="highlighted">Object.keys()</kbd> method returns the array of a specified object's own enumerable property names. The property order is the same as in the case of looping over the properties of the object manually.

The hasOwnProperty() Method

The <kbd class="highlighted">hasOwnProperty()</kbd> method returns a boolean value that indicates if the object has the specified property as its own property or not. It returns true if the property exists as an own property of the object, and false otherwise.