If you are working with REST services using the $.ajax method of jQuery, the chances are high that you might be receiving 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 index will store the index of the array in each iteration and 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 "searchable inde 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.
You may also like: