How to List the Properties of a JavaScript Object

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

You can use the built-in Object.keys method which is supported in the modern browsers:

let keys = Object.keys(myObj);

Example:

let object = {
  name: 'Jack',
  age: 25
};
let keys = Object.keys(object)
console.log(keys);

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

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

Example:

let getKeys = function (obj) {
  let keysArr = [];
  for (var key in obj) {
    keysArr.push(key);
  }
  console.log(keysArr);
}
let obj = {
  name: 'Jack',
  age: 25
}
getKeys(obj);

Alternatively, you can replace var getKeys with Object.prototype.keys to allow you to call .keys() on any object. However, extending the prototype has some 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 it, 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 hasOwnProperty() method like this:

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

Example:

let user = {
  name: 'Jack',
  age: 25
}
if (user.hasOwnProperty("name")) {
  console.log(user.name);
}

The Object.keys() method

The Object.keys() 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 hasOwnProperty() method returns a boolean value that indicates if the object has the specified property as its own property or not. If the object contains the "key" property, a function is created. This would return true if it could find no keys in the loop, meaning the object is empty. If any key is found, the loop breaks returning false.

Do you find this helpful?

Related articles