Monday, May 13, 2013

Accessing Objects and Arrays in JavaScript


Hi friends, I have illustrated the way of accessing an object and array in JavaScript using for loop.

We have an object variable called "info"


 var info = {
            "full_name": "Tchelen Lilian Costa Nakarmi",
            "title": "Staff Author",
            "links": [
                { "blog": "http://tchelennakarmi.blogspot.com" },
                { "facebook": "http://facebook.com" },
                { "google": "www.google.com" },
                { "twitter": "http://twitter.com/" },
                { "youtube": "http://www.youtube.com/" }
                ]
        };

It has three properties as shown below.
  1. full_name:  is an object
  2. title: is an object
  3. links: an array of object
We use indexed for loop to traverse through properties of "info" object 
 for (var i = 0; i < info.links.length; i++) {
................................
}
We use iterative for loop to traverse through properties of objects inside "links" array.
for (key in info.links[i]) {
...................................
}

The traversed items, viz. key value pair of object is appended to a string called output in a form of ordered list item. And we finally assign this output string to the innerHTML of the order list. 

Below is the full code and output. 

_________________________________________________________________________________

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Accessing Objects</title>
</head>
<body>
    <h2>Links</h2>

    <ol id="links">

    </ol>

    <script>
        var info = {
            "full_name": "Ray Villalobos",
            "title": "Staff Author",
            "links": [
                { "blog": "http://iviewsource.com" },
                { "facebook": "http://facebook.com/iviewsource" },
                { "podcast": "http://feeds.feedburner.com/authoredcontent" },
                { "twitter": "http://twitter.com/planetoftheweb" },
                { "youtube": "http://www.youtube.com/planetoftheweb" }
                ]
        };

        var output = '';

        for (var i = 0; i < info.links.length; i++) {
            for (key in info.links[i]) {
                if (info.links[i].hasOwnProperty(key)) {
                    output += '<li>' +
                        '<a href="' + info.links[i][key] + '">' + key + '</a>' +
                        '</li>';
                }
            }   //for each object
        }       //for each array

        var update = document.getElementById('links');
        update.innerHTML = output;
    </script>

</body>
</html>
________________________________________________________________________________


No comments:

Post a Comment