JQuery Create and Access Multiple Objects

From CoderLearner
Jump to: navigation, search

Description

Multiples array and object within another object.

Syntax


var users = {
                    name: ["bob", "john", "janny"],
                    age: [23, 45, 33],
                    location: ['Houston,Tx', 'Auckland, NZ', 'Singapore,Singapore']
            };
  • Access Object

        $('#show_text').html(users.name[0]+" is "+ users.age[0] 
                       + " year old and from "+ users.location[0] );
 

Example


<html>
    <head>
        <title>Object</title>
        <script type="text/javascript" src="/js/jquery-1.8.3.js"></script>
        <script type="text/javascript">
            $().ready(function() {
                var users = {
                    name: ["bob", "john", "janny"],
                    age: [23, 45, 33],
                    location: ['Houston,Tx', 'Auckland, NZ', 'Singapore,Singapore']
                };

                for (u in users) {
                     $('#show_text').append(u + " contains " + users[u].join(',') + "<br/>");
                }
                 
            });
        </script>
    </head>
    <body>
        <div id="show_text"></div>
    </body>
</html>

Result

name contains bob,john,janny
age contains 23,45,33
location contains Houston,Tx,Auckland, NZ,Singapore,Singapore

Example 2

  • Use $.each()

                $.each(users, function(key, values) {
                    $('#show_text').append(key + " contains " + values.join(',') + "<br/>");

                });

Example 3

  • Loop through each object values

                $.each(users, function(key, values) {
                    $('#show_text').append(key + " contains: ");
                   // loop through each object values
                    for(var i=0; i < values.length; i++) {
                          $('#show_text').append(values[i]+" ");
                    };

                    $('#show_text').append("<br/>");

                });