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:
- Create an object variable and assign values to it
- Create an variable which shows the size
- 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.
<script> var object1= { "rajnish":"singh", "sanjeev":"sharma", "suraj":"agrahari", "yash":"khandelwal" }; var count= Object.keys(object1).length; document.write(count); </script> |
chevron_right
filter_none
Output: 4
Another way to get the size of the javascript object is:
-
Approach-2:
- Create an object variable and assign values to it
- Create an variable which shows the size
- 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.
<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
filter_none
Output: 4


