Categories
JavaScript Answers

How to count the number of properties in a JavaScript object?

Spread the love

Sometimes, we want to count the number of properties in a JavaScript object.

In this article, we’ll look at how to count the number of properties in a JavaScript object.

How to count the number of properties in a JavaScript object?

To count the number of properties in a JavaScript object, we can use the Object.entries method.

For instance, we write:

const member = {
  "mother": {
    "name": "Mary",
    "age": "38"
  },
  "father": {
    "name": "Bill",
    "age": "40"
  },
  "brother": {
    "name": "Alex",
    "age": "10"
  }
}

const {
  length
} = Object.entries(member)
console.log(length)

to call Object.entries with member to return an array of key-value pair arrays obtained from member.

Then we use the length property of the returned array to get the number of properties in member.

Therefore, length is 3.

Conclusion

To count the number of properties in a JavaScript object, we can use the Object.entries method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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