谷歌图表,将dataTable行追加到其他dataTable

时间:2017-02-06 11:05:56

标签: javascript jquery datatable google-visualization

我有2个google.visualization.DataTable(数据)

我想将1个dataTable的行追加到另一个dataTable。

我该怎么做?

示例表1:

1 | test1 | 20

2 | test2 | 30

示例表2:

3 | test3 | 60

4 | test4 | 40

我想将2合并到:

1 | test1 | 20

2 | test2 | 30

3 | test3 | 60

4 | test4 | 40



google.charts.load('current', {
  callback: drawChart,
  packages:['table']
});

var json1 = {
  "cols": [
        {"id":"","label":"Topping","pattern":"","type":"string"},
        {"id":"","label":"Slices","pattern":"","type":"number"}
      ],
  "rows": [
        {"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
        {"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
        {"c":[{"v":"Olives","f":null},{"v":1,"f":null}]}
      ]
}

var json2 = {
  "cols": [
        {"id":"","label":"Topping","pattern":"","type":"string"},
        {"id":"","label":"Slices","pattern":"","type":"number"}
      ],
  "rows": [
        {"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
        {"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
      ]
}
function drawChart() {

  var oldData = new google.visualization.DataTable(json1);
  var appendData = new google.visualization.DataTable(json2);
  
  /// somehow append rows of appendData to olddata here
  
  var newData = new google.visualization.DataTable(json1); // needs to be changed to he combined data
  var chart = new google.visualization.Table(document.getElementById('chart_div'));
  chart.draw(oldData);
};

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

来自另一个问题的相同脚本似乎产生了期望的结果

请参阅以下工作代码段...

google.charts.load('current', {
  callback: drawChart,
  packages:['table']
});

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['x', 'y1', 'y2'],
    [1, 'test1', 20],
    [2, 'test2', 30],
  ]);

  var data1 = google.visualization.arrayToDataTable([
    ['x', 'y1', 'y2'],
    [3, 'test3', 60],
    [4, 'test4', 40],
  ]);

  var keys = [];
  for (var i = 0; i < data.getNumberOfColumns(); i++) {
    keys.push([i, i]);
  }

  var joinData = new google.visualization.data.join(
    data,
    data1,
    'full',
    keys,
    [],
    []
  );

  var chart = new google.visualization.Table(document.getElementById('chart_div'));
  chart.draw(joinData);
};
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>