Search code examples
javascriptforeachgoogle-datatable

iterate through all datatable objects in a page?


I have a webpage that displays graphs using Google Charts. I've created multiple DataTables as below :

var rttldata1 = new google.visualization.DataTable();
var rttldata2 = new google.visualization.DataTable();
var rttldata3 = new google.visualization.DataTable();
...
var rttldata10 = new google.visualization.DataTable();

At a certain point, I want to do something to all of these tables with javascript.

Something like

for each (datatable){
    do something
}

Can some one point me in the right direction please?


Solution

  • First you will want to encapsulate the instantiation of each DataTable within a function to stay DRY and add to an array. Then you can loop through each object.

    var tables = [];
    
    function makeDataTable(options) {
      var options = options || {};
      var table = new google.visualization.DataTable(options);
      tables.push(table);
      return table; // not needed in this context, but you might want
    }
    
    // insert code that creates tables via makeDataTable({}) ...
    
    for (var i = 0, max = tables.length; i < max; i += 1) {
      var currTable = tables[i];
      // do something with currTable
    }