iterate json array in javascript [duplicate]

Your JSON has 2 top-level elements. So, you can’t logically iterate across the entire document (without flattening it).

But you can iteration across the “MATHS” and “LOGICAL REASONING” elements.

For example, using underscore:

_(data.MATHS).each(function(item) {
  var section = item.SECTION;
  var type = item.TYPE;
  var count = item.COUNT;

  // Now do something with them
});

Note the different access method to the ‘LOGICAL REASONING’ element, because of the space.

_(data['LOGICAL REASONING').each(function(item) {
  var section = item.SECTION;
  var type = item.TYPE;
  var count = item.COUNT;

  // Now do something with them
});

If you wanted all the data together, one way of doing it would be:

var flattened = _.union(data.MATHS, data['LOGICAL REASONING']);

_(flattened).each(function(item) {
  // Process...
});

Check out the underscore docs for some more information about the possibilities. Many ways to skin a cat.

http://underscorejs.org/

Cheers.

Leave a Comment