How to get the size of a JavaScript object ?
Last Updated :
12 Jan, 2024
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:
- We can get the size of the javascript object with the help of Object.keys() method.
- Create an object variable and assign values to it
- Create a variable that shows the size
- Call the Object.keys(object-name).length and assign it to the variable (in step 2).
Syntax:
Object.keys(object_name);
Example: To get the size of a javascript object by Object.keys() method.
JavaScript
let object1= { "rajnish" : "singh" ,
"sanjeev" : "sharma" ,
"suraj" : "agrahari" ,
"yash" : "khandelwal"
};
let count= Object.keys(object1).length;
console.log(count);
|
Using Object.objsize() method
- Create an object variable and assign values to it
- Create a variable that shows the size
- Pass the object name to Object.objsize which further enters the function that calculates and returns the size and assigns it to the variable.
Example: This example shows the implementation of the above-explained approach.
JavaScript
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);
|
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.
JavaScript
let object1 = {
"rajnish" : "singh" ,
"sanjeev" : "sharma" ,
"suraj" : "agrahari" ,
"yash" : "khandelwal"
};
let length = Object.entries(object1).length
console.log(length);
|
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.
JavaScript
let object1 = {
"rajnish" : "singh" ,
"sanjeev" : "sharma" ,
"suraj" : "agrahari" ,
"yash" : "khandelwal"
};
let length = Object.values(object1).length
console.log(length);
|
Share your thoughts in the comments
Please Login to comment...