![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Length of a JavaScript object?
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
Advertisements