How to get the size of a JavaScript object?

We can get size of java script object with the help of Object.keys() method.

Syntax:

Object.keys(object_name)
    Parameter:

  • object_name

Return Value: an array of all the object’s own enumerable property keys.

    Approach-1:



  1. Create an object variable and assign values to it
  2. Create an variable which shows the size
  3. Call the Object.keys(object-name).length and assign it to the variable (in step 2).

Example-1: To get size of javascript object by Object.keys() method.

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
var object1= { "rajnish":"singh",
               "sanjeev":"sharma",
               "suraj":"agrahari",
               "yash":"khandelwal"
             };
var count= Object.keys(object1).length;
document.write(count);
</script>

chevron_right


Output: 4

Another way to get the size of the javascript object is:

    Approach-2:

  1. Create an object variable and assign values to it
  2. Create an variable which shows the size
  3. Pass the object-name to Object.objsize which further enters to the function which calculates and returns the size and assign it to the variable.
filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
Object.objsize = function(obj)
    {
    var size = 0, key;
  
    for (key in obj)
        {
       if (obj.hasOwnProperty(key))
         size++;
             }
  
    return size;
  
    };
  
var object1 = { "rajnish":"singh",
            "sanjeev":"sharma",
        "suraj":"agrahari",
        "yash":"khandelwal"
          };
  
var count = Object.objsize(object1);
document.write(count);                    
</script>

chevron_right


Output: 4

full-stack-img




My Personal Notes arrow_drop_up

Recommended Posts:

    Article Tags :

    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.