Open In App

How to get the size of a JavaScript object ?

In this article, we will see the methods to find the size of a JavaScript object.

These are the following ways to solve the problem:



Using Object.keys() method

Syntax:

Object.keys(object_name);

Example: To get the size of a javascript object by Object.keys() method. 






let object1= { "rajnish":"singh",
               "sanjeev":"sharma",
               "suraj":"agrahari",
               "yash":"khandelwal"
             };
let count= Object.keys(object1).length;
console.log(count);

Output
4

Using Object.objsize() method

Example: This example shows the implementation of the above-explained approach.




Object.objsize = function(obj) {
    let size = 0, key;
  
    for (key in obj) {
        if (obj.hasOwnProperty(key))
        size++;
    }
    return size;
};
  
let object1 = { "rajnish":"singh",
                "sanjeev":"sharma",
                "suraj":"agrahari",
                "yash":"khandelwal"
              };
  
let count = Object.objsize(object1);
console.log(count);

Output
4

Using Object.entries() method

In this approach, we are using Object.entries() method. after passing the given object into this method by calling length property of the object we are getting the length of the object.

Example: This example shows the implementation of the above-explained approach.




let object1 = {
    "rajnish": "singh",
    "sanjeev": "sharma",
    "suraj": "agrahari",
    "yash": "khandelwal"
};
  
let length = Object.entries(object1).length
console.log(length);

Output
4

Using Object.values() method

In this approach, we are using Object.values() method. after passing the given object into this method by calling length property of the object we are getting the length of the object.

Example: This example shows the implementation of the above-explained approach.




let object1 = {
    "rajnish": "singh",
    "sanjeev": "sharma",
    "suraj": "agrahari",
    "yash": "khandelwal"
};
  
let length = Object.values(object1).length
console.log(length);

Output
4

Article Tags :