JavaScript object Array length | Example code

How can I find the length of all properties contained on an array of objects?

Use reduce method on each iteration, add the number of keys of the current object to the accumulator, to sum up the keys of every item:

JavaScript object array length Example

HTML example code:

<!DOCTYPE HTML> 
<html> 
<body> 

	<script>
		const users = [
		{
			firstName: "Bruce",
			lastName: "Wayne",
			id: "1",
		},

		{
			firstName: "Peter",
			lastName: "Parker",
			id: "2"
		},

		{
			firstName: "Tony",
			lastName: "Stark",
			id: "3"
		}
		];

		const totalProps = users.reduce((a, obj) => a + Object.keys(obj).length, 0);
		console.log(totalProps);
		
	</script>
</body> 
</html>	

Output:

Use length property to get the number of keys present in the object

objectLength = Object.keys(exampleObject).length

Complete example code

<!DOCTYPE HTML> 
<html> 
<body> 

	<script>
		const users = [
		{
			firstName: "Bruce",
			lastName: "Wayne",
			id: "1",
		},

		{
			firstName: "Peter",
			lastName: "Parker",
			id: "2"
		},

		{
			firstName: "Tony",
			lastName: "Stark",
			id: "3"
		}
		];

		objectLength = Object.keys(users).length
		console.log(objectLength);
		
	</script>
</body> 
</html>		

Output: 3

Do comment if you have any doubts and suggestions on JS Array Object 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.