I have some json (var data
)that looks like this:
{"success":"true","keywords":["firstkeyword","secondkeyword"]}
And im trying to loop through the keywords using this code:
data.keywords.each(function(e){
$('#campaign_keywords').append("<p>"+e+"</p>");
});
But i get the error
Uncaught TypeError: Object firstkeyword,secondkeyword has no method 'each'
The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.
Looping Using JSON JSON stands for JavaScript Object Notation. It's a light format for storing and transferring data from one place to another. So in looping, it is one of the most commonly used techniques for transporting data that is the array format or in attribute values.
Answer: Use the jQuery. each() function each() or $. each() can be used to seamlessly iterate over any collection, whether it is an object or an array. However, since the $. each() function internally retrieves and uses the length property of the passed array or object.
You need to loop through it like this:
$.each(data.keywords, function (i, v) {
$('#campaign_keywords').append("<p>"+data.keywords[i]+"</p>");
});
jQuery.each()
That's because it's an array and it needs to be a jquery wrapped object in order to use jquery functions. Try:
$.each(data.keywords, function(index, value){...});
Its a javascript array, not jQuery object. just apply $ over it to make it jquery object like
$(data.keywords).each(function(e){
$('#campaign_keywords').append("<p>"+e+"</p>");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With