最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Updating Data in Google Visualization DataTable - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Nov 16, 2018 at 16:04 Bikash kharel 5217 silver badges19 bronze badges asked Nov 13, 2012 at 17:26 Josh JohnsonJosh Johnson 11.1k14 gold badges64 silver badges85 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

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./chart/interactive/docs/reference#DataTable and holds a bunch a good examples.

发布评论

评论列表(0)

  1. 暂无评论