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

6 comments:

  1. Why there isn't any "DISLIKE" button?

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. 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/

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

    ReplyDelete
  5. Thanks very useful code snippet

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

    ReplyDelete