0

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() { ...
Aaron Dufour
  • 17,288
  • 1
  • 47
  • 69
coiso
  • 7,151
  • 12
  • 44
  • 63

3 Answers3

2

Two suggestions.

  1. JSON is just text. You have an actual JavaScript array, once you remove the outer curly braces from your code.

  2. 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.

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
  • forEach isn't cross browser compatible, so you could either shim or use the more generic `for(counter initialisation; counter condition; counter increment)` structure – Asad Saeeduddin Oct 20 '12 at 21:35
  • Strictly speaking this is true, but looking at http://kangax.github.com/es5-compat-table/ the only browser that doesn't support it is IE <= 8. – Ray Toal Oct 20 '12 at 21:38
  • Many people would dispute the browserness of IE <= 8 :-) – LSerni Oct 20 '12 at 21:40
2

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
   }
}
LSerni
  • 55,617
  • 10
  • 65
  • 107
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" }
                  ];
charlietfl
  • 170,828
  • 13
  • 121
  • 150