Updating Data in Google Visualization DataTable

Josh Johnson picture Josh Johnson · Nov 13, 2012 · Viewed 14.6k times · Source

How do you update data in a google visualization datatable? Example:

var data = new google.visualization.DataTable();

data.addColumn('string', 'Name');
data.addColumn('string', 'Occupation');

data.addRow(['Bob', 'Shoe Wearer']);
data.addRow(['Henry', 'Transformer']);
data.addRow(['Betty', 'Seltzer Connoisseur']);

// Time passes and Bob changes jobs:
data.addRow(['Bob', 'Beach Comber']);

Of course, that adds a new row and now I have two Bobs. How can I update Bob's occupation?

Answer

HansMaulwurf picture HansMaulwurf · Nov 20, 2012

As Bob is the first row you inserted, his occupation resides in row with index 0 and column with index 1:

data.setValue(0, 1, 'Beach Comber');

In case you don't know the row index of a person who's occupation is to be updated, I suggest iterating or filtering to find all Bob rows (or the one Bob row in your case). Iteration is the 'brute force' way and goes like this

for (var y = 0, maxrows = data.getNumberOfRows(); y < maxrows; y++) {
    if (data.getValue(y, 0) == 'Bob') {
        data.setValue(y, 1, 'Beach Comber');
    }
}

Filtering is more elegant:

var foundRows = data.getFilteredRows([{column: 0, value: 'Bob'}]);
for (var y = 0, maxrows = foundRows.length; y < maxrows; y++) {
     data.setValue(foundRows[y], 1, 'Beach Comber');
}

The reference API-Doc can be found here: https://developers.google.com/chart/interactive/docs/reference#DataTable and holds a bunch a good examples.