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" >
<
head>
<
title>Loop JavaScript Object by DevCurry.com</title>
<
script type="text/javascript">
var
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>');
}

</script>
</
head>
<
body>
</body>
</
html>

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:

image






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

6 comments:

Anonymous said...

Why there isn't any "DISLIKE" button?

Test said...
This comment has been removed by the author.
Test 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...

http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/

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.