Loop Object literal using JavaScript

Here’s how to loop a JavaScript object literal and apply conditions to filter the object

<html xmlns="http://www.w3.org/1999/xhtml" >
title>Loop JavaScript Object by DevCurry.com</title>
script type="text/javascript">
jObj = [
{ "ID": "1", "Name": "Keith", "Age": "32" },
{ "ID": "2", "Name": "Bill", "Age": "36" },
{ "ID": "3", "Name": "Jack", "Age": "25" },
{ "ID": "4", "Name": "Mary", "Age": "39" },
{ "ID": "5", "Name": "Pallav", "Age": "29" }

var cnt = jObj.length;

for (var i = 0; i < cnt; i++) {
if (jObj[i].Age >= 30)
document.write(jObj[i].Name +
' ' + jObj[i].Age + '</br>');


As you can see, in the code shown above, we loop through the JavaScript object literal and print only those names whose age is >= 30. This will only print 3 out of 5 names and the output is as shown below:


Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal


Anonymous said...

Why there isn't any "DISLIKE" button?

Elijah Manor said...
This comment has been removed by the author.
Elijah Manor said...

You might consider updating the title to "Loop an Object Literal using JavaScript".

JSON is a serialized form of JavaScript (think of XML that represents a .NET object). The Object Literal syntax looks very similar to JSON, but there are differences and conceptually they are different.

You can check out Ben Alman's post for extensive details...


Suprotim Agarwal said...

Thanks Elijah. Point taken and the post was updated with the suggestions.

Anonymous said...

Thanks very useful code snippet

asp.net ecommerce development said...

Thanks for sharing this code. I would like to implement it practically. Hope it will run successfully.