How to Count the Number if Keys/Properties of a JavaScript object

As a programmer, you might have come across situations where you need to count the number of keys or properties in a JavaScript object.

In this Javascript tutorial, we’ll go through various methods of counting the properties in a JavaScript object.

We’ll start with the simplest method and then move on to the more advanced methods.


Using the Object.keys() Method

The simplest and most straightforward way to count the properties in an object is to use the Object.keys() method.

This method returns an array of the object’s own enumerable properties.

The Array.length property can then be used to determine the number of properties in the object.

Here’s an example:

const obj = {
  name: 'John Doe',
  age: 30,
  location: 'New York'
};

const count = Object.keys(obj).length;

console.log(count); // 3

Using a For…In Loop

Another way to count the properties in an object is to use a for...in loop.

This method iterates over the enumerable properties of an object and increments a counter for each property.

Here’s an example:

const obj = {
  name: 'John Doe',
  age: 30,
  location: 'New York'
};

let count = 0;
for (const key in obj) {
  count++;
}

console.log(count); // 3

Using Object.values()

The Object.values() method can also be used to count the properties of an object.

This method returns an array of the object’s own enumerable property values.

The Array.length property can then be used to determine the number of properties in the object.

Here’s an example:

const obj = {
  name: 'John Doe',
  age: 30,
  location: 'New York'
};

const count = Object.values(obj).length;

console.log(count); // 3

Using Object.entries()

The Object.entries() method can also be used to count the properties of an object.

This method returns an array of arrays containing the object’s own enumerable property [key, value] pairs.

The Array.length property can then be used to determine the number of properties in the object.

Here’s an example:

const obj = {
  name: 'John Doe',
  age: 30,
  location: 'New York'
};

const count = Object.entries(obj).length;

console.log(count); // 3

Conclusion

In this tutorial, we went through four methods for counting the properties in a JavaScript object.

From the simplest Object.keys() method to the more advanced Object.entries() method, there are many ways to determine the number of properties in an object.

Choose the method that works best for your specific use case and make sure to utilize the right tool for the job.

Editorial Team
Editorial Team

Programming Cube website is a resource for you to find the best tutorials and articles on programming and coding.