JQuery Access Object

From CoderLearner
Jump to: navigation, search

Description

Access or loop through the object.

Syntax

    var users = {name:"Bob", age:39} ;
  • for loop
       for(u in users) {
           console.log(u)   // key  
           console.log(users[u] )// value
        }
  • $.each() loop
         $.each(users,function(key, value) {
             console.log(key); // name, age
             console.log(value); // Bob, 39
         });

Example

<html>
    <head>
        <title>Object</title>
        <script type="text/javascript" src="/js/jquery-1.8.3.js"></script>
    </head>
    <body>
        <script type="text/javascript">
            $().ready(function() {
                var users = {name:"Bob", age:39} ;

                for (u in users) {
                    var tmp = [u] + " is  "+ users[u] + "<br/>";
                    $('#show_text').append(tmp);
                }
            });
        </script>

        <div id="show_text"></div>
    </body>
</html>


Result

name is Bob
age is 39