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:
- 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
Recommended Posts:
- How to set font size based on window size using JavaScript ?
- How to access an object having spaces in the object's key using JavaScript ?
- How to check a JavaScript Object is a DOM Object ?
- Object.is( ) in JavaScript
- Map vs Object in JavaScript
- How to get the first key name of a JavaScript object ?
- How to get a key in a JavaScript object by its value ?
- How to clone a JavaScript object?
- JavaScript | Object Properties
- Rename object key in JavaScript
- Object.values( ) In JavaScript
- Object.create( ) In JavaScript
- JavaScript | Object Methods
- JavaScript | Object Constructors
- How to iterate over a JavaScript object ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



