Let’s say the following is our Student object −
var studentObject = new Object(); studentObject["studentFirstName"] = "John"; studentObject["studentLastName"] = "Doe"; studentObject["studentAge"] = 22; studentObject["studentCountryName"] = "US"; studentObject["studentCollegeName"] = "MIT"; studentObject["studentSubjectName"] = "JavaScript";
Let’s find the length.
You can use the concept of keys available in object and if the key is present then increment the counter variable and return the counter after completing the for loop.
Example
var studentObject = new Object(); studentObject["studentFirstName"] = "John"; studentObject["studentLastName"] = "Doe"; studentObject["studentAge"] = 22; studentObject["studentCountryName"] = "US"; studentObject["studentCollegeName"] = "MIT"; studentObject["studentSubjectName"] = "JavaScript"; Object.findLength = function (stObject) { var counter = 0, k; for (k in stObject) { if (stObject.hasOwnProperty(k)) counter++; } return counter; }; var lengthOfStudentObject = Object.findLength(studentObject); console.log("The length Student Object is=" + lengthOfStudentObject);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo191.js.
Output
This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo191.js The length Student Object is=6