Signup/Sign In
LAST UPDATED: APRIL 28, 2023

How to Loop through an Array/Object in jQuery?

Technology #jQuery

    How to Loop through an Array/Object in jQuery?

    If you are working with REST services using the $.ajax method of jQuery, the chances are high that you might be receiving a JSON array as a response or if for some other reason, you have to iterate over an Array in jQuery to process data elements or display the data you can use the jQuery.each() function, which we will be covering in this article.

    jQuery.each() or $.each() Function

    This is the simplest way of looping around an array or a JSON array in JavaScript or jQuery. Of course, you can use the for loop but that is so old school.

    Here is the syntax of jQuery.each() function:

    jQuery.each(array, callback)
    
    // or for objects it can be used as
    
    jQuery.each(object, callback)
    

    where, array parameter will have the array and the callback will be a function with parameters index and item, where the index will store the index of the array in each iteration and the item will store the data element.

    and in the second case, object parameter will have the object and the callback will be a function with parameters propName and propValue, where propName will store the name of the object attribute in each iteration and propValue will store the attribute value for the object.

    Let's take an example,

    var arr = [1, 2, 3, 4];
    $.each(arr , function(index, val) { 
      console.log(index, val);
    });
    

    Output:

    0 1
    1 2
    2 3
    3 4

    In the code example above we iterated over a simple array with values. But what if we have an object with string key-value pairs, for example {foo:"bar"}, then how will we iterate over it.

    var someObj = { foo: "bar"};
    
    $.each(someObj, function(propName, propVal) {
      console.log(propName, propVal);
    });
    

    Output:

    foo bar

    See, how simple it is to loop around an array or an object or a JSON array using the $.each() function.

    Wait, but we haven't covered JSON array yet, let's see an example for that too.

    var agents = [
                   {
                      "id": "007",
                      "agent": "James Bond"
                   },                  
                   {
                      "id": "006",
                      "agent": "John Wick"
                   }
                 ]
    // iterate over the JSON array
    $.each(agents , function(index, item) { 
        console.log("Agent Id: " + item.id);
        console.log("Agent Name: " + item.agent);
    });

    Output:

    Agent Id: 007
    Agent Name: James Bond
    Agent Id: 006
    Agent Name: John Wick
    

    Conclusion

    Hope this post helped you, sometimes while using this function for iterating over JSON arrays you may get a "searchable index not available" error, in such case use the $.parseJSON() function to first parse your JSON array and then try to loop through it.

    If you get any error, you can ask in the comment section below.

    Frequently Asked Questions(FAQs)

    1. How do you loop an array of objects?

    To loop through an array of objects in JavaScript, you can use a for loop or a forEach method. Here's an example using a for loop:

    var myArray = [  { name: 'John', age: 30 },  { name: 'Jane', age: 25 },  { name: 'Bob', age: 40 }];
    
    for (var i = 0; i < myArray.length; i++) {
      console.log(myArray[i].name);
    }
    

    This code will loop through the array and log each object's name property to the console.

    2. How to create array in the jQuery loop?

    To create an array in a jQuery loop, you can use the push method to add new elements to the array. Here's an example:

    var myArray = [];
    
    $('li').each(function() {
      myArray.push($(this).text());
    });
    
    console.log(myArray);
    

    This code will loop through all the li elements on the page and add their text content to the myArray array using the push method.

    3. How to create an array object in jQuery?

    To create an array object in jQuery, you can use the $.map method to transform an array of values into an array of objects. Here's an example:

    var myArray = ['John', 'Jane', 'Bob'];
    
    var newArray = $.map(myArray, function(value, index) {
      return { name: value, id: index };
    });
    
    console.log(newArray);
    

    This code will create a new array of objects with the name property set to the value from the original array, and the id property set to the index of the value in the original array.

    4. How to loop through array of JSON object in JavaScript?

    To loop through an array of JSON objects in JavaScript, you can use a for loop or a forEach method. Here's an example using a for loop:

    var myArray = [  { name: 'John', age: 30 },  { name: 'Jane', age: 25 },  { name: 'Bob', age: 40 }];
    
    for (var i = 0; i < myArray.length; i++) {
      console.log(myArray[i].name + ' is ' + myArray[i].age + ' years old.');
    }
    

    You may also like:

    This is the official profile of the Studytonight content team.
    IF YOU LIKE IT, THEN SHARE IT
    Advertisement

    RELATED POSTS