ADVERTISEMENT
ADVERTISEMENT

Length of a JavaScript object

Learn how to find the length of a JavaScript object using various methods?
Submitted by Pratishtha Saxena, on April 30, 2022

As we already know, an object in JavaScript is a variable or a variable with some properties in it.

Example:

 var person ={
    'name':'John',
    'age':'25'
};

In above example, person is an object with properties name and age.

To find the length of an object, there are following ways:

1) Using Object.keys() Method

This method will return the properties of the object as an array and length will print the length of that array i.e., the length of the object.

Example 1:

var universe = {
	'star': 'Sun',
	'planet': 'Earth',
	'satellite': 'Moon'
};

console.log(Object.keys(universe).length);

Output:

3

2) Using hasOwnProperty() Method

With the help of a loop, this method will check whether the key is present in the object or not. If the key is present then it will Boolean value (True/False) which then will increment the count variable.

Example 2:

var universe = {
	'star': 'Sun',
	'planet': 'Earth',
	'satellite': 'Moon'
};

var key, count = 0;

for (key in universe) {
	if (universe.hasOwnProperty(key))
		count++;
}
objectlength = count;

console.log(objectlength);

Output:

3

JavaScript Examples »


ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.