JSON array :
var json_array = [
{ "A" : "1" },
{ "B" : "2" }
];
How can I make a JS function that acts on every element of the array? Like..
$.each(json_array, function() { ...
JSON array :
var json_array = [
{ "A" : "1" },
{ "B" : "2" }
];
How can I make a JS function that acts on every element of the array? Like..
$.each(json_array, function() { ...
Two suggestions.
JSON is just text. You have an actual JavaScript array, once you remove the outer curly braces from your code.
Don't use JQuery for this. The plain old JavaScript forEach
already works on regular arrays, which is, what I think, you want.
ADDENDUM
Using JavaScript's forEach
:
var a = [
{"A": "1"},
{"B": "2"}
];
a.forEach(function(x) {
alert(JSON.stringify(x));
});
If you have an old browser (IE <= 8), replace the forEach
call with (suggestion due to Asad):
for (var i = 0, n = a.length; i < n; i += 1) {
// do something with the element object
}
JQuery's each
is for jQuery objects.
If you can't use jQuery, then why don't you just loop the array?
for (i = 0; i < json_array.length; i++)
{
var item = json_array[i]; // this is { "A": 1 }
for (element in item)
{
// element is "A", item[element] is 1
}
}
Using the jQuery each
$.each(json_array, function( index, item) {
alert( item.A};
})
The keys in each object within the array are typically the same which your demo isn't so this would work for:
var json_array = [
{ "A" : "1" },
{ "A" : "2" }
];