JQuery Loop $.each()

$.each() function is not the same as $(selector).each(), It has different meaning and usage.


        $(function () {
            var persons = []; //array of person
            var person1 = { “Id”: “101”, “Name”: “Mr. X” }; //person object
            var person2 = { “Id”: “102”, “Name”: “Mr. Y” }; //person object
            var person3 = { “Id”: “103”, “Name”: “Mr. Z” }; //person object

            persons.push(person1); persons.push(person2); persons.push(person3);

            ////Looping persons array without any function parameter
            $.each(persons, function () {
                console.log(‘Id-‘ + this.Id + ‘, Name-‘ + this.Name);
            });

            ////Looping persons array with function parameter
            $.each(persons, function (index, person) {
                console.log(‘Sl-‘ + index + ‘, Id-‘ + person.Id + ‘, Name-‘ + person.Name);
                $.each(person, function (key, value) {
                    console.log(key + ‘:’ + value);
                });
            });

            //Looping person object, it’ll loop through property(s).
            $.each(person1, function (key, value) {
                console.log(key + ‘ :  ‘ + value);
                //Output=============
                //Id :  101 
                //Name :  Mr. X 
                //===================
            });


            //It can be done in JavaScript also
            persons.forEach(function (person) {
                console.log(‘Id-‘ + person.Id + ‘, Name-‘ + person.Name);

            });
        });

   
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s