JavaScript length of an object | Example code

You can use Object.keys() to get the length of the object in JavaScript. This doesn’t have to modify any existing prototype since Object.keys() is now built-in.

Let’s see HTML example code:

Sort way

Here’s an update as of 2016 and the widespread deployment of ES5 and beyond. For IE9+ and all other modern ES5+ capable browsers.

<!DOCTYPE HTML> 
<html> 
<body> 

	<script>
		const myObject = new Object();
		myObject["firstname"] = "John";
		myObject["lastname"] = "Ken";
		myObject["age"] = 21;

		var size = Object.keys(myObject).length;

		console.log(size);
	</script>
</body> 
</html>		

Creating a function for get the length of object.

<!DOCTYPE HTML> 
<html> 
<body> 

	<script>
		const myObject = new Object();
		myObject["firstname"] = "John";
		myObject["lastname"] = "Ken";
		myObject["age"] = 21;

		Object.size = function(obj) {
			var size = 0,
			key;
			for (key in obj) {
				if (obj.hasOwnProperty(key)) size++;
			}
			return size;
		};

		// Get the size of an object
		var size = Object.size(myObject);

		console.log(size);
	</script>
</body> 
</html>		

Output:

JavaScript length of an object

Same code for Object Array

<!DOCTYPE HTML> 
<html> 
<body> 

	<script>
		let cars = [
		{
			"color": "purple",
			"type": "minivan",
			"registration": new Date('2017-01-03'),
			"capacity": 7
		},
		{
			"color": "red",
			"type": "station wagon",
			"registration": new Date('2018-03-03'),
			"capacity": 5
		}];

		Object.size = function(obj) {
			var size = 0,
			key;
			for (key in obj) {
				if (obj.hasOwnProperty(key)) size++;
			}
			return size;
		};

		// Get the size of an object
		var size = Object.size(cars);

		console.log(size);
	</script>
</body> 
</html>		

Output: 2

Do comment if you have any doubts and suggestions on this JS Object Array topic.

Note: All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.