JQuery $.each traverses an instance of a JavaScript array object

  • 2020-03-30 03:47:49
  • OfStack

See a simple jQuery example to iterate over a JavaScript array object.


var json = [
{"id":"1","tagName":"apple"},
{"id":"2","tagName":"orange"},
{"id":"3","tagName":"banana"},
{"id":"4","tagName":"watermelon"},
{"id":"5","tagName":"pineapple"}
];

$.each(json, function(idx, obj) {
alert(obj.tagName);
});

The code snippet above works and says "apple", "orange"... Etc., as expected.
Problem: JSON strings

In the following example, you declare a JSON string (with single or double quotes) directly.


var json = '[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},
{"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},
{"id":"5","tagName":"pineapple"}]';

$.each(json, function(idx, obj) {
alert(obj.tagName);
});

In Chrome, it displays errors under the console:

Uncaught TypeError: Cannot use 'in' operator to search for '156'
In [{" id ":" 1 ", "tagName" : "apple"}...

Solution: convert JSON strings into JavaScript objects.
To fix it, convert it to a JavaScript object through the standard json.parse () or $.parsejson of jQuery.


var json = '[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},
{"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},
{"id":"5","tagName":"pineapple"}]';

$.each(JSON.parse(json), function(idx, obj) {
alert(obj.tagName);
});

//or 

$.each($.parseJSON(json), function(idx, obj) {
alert(obj.tagName);
});

Related articles: