【问题标题】:Easy way to see if DataView is empty?查看 DataView 是否为空的简单方法?
【发布时间】:2013-03-18 12:23:34
【问题描述】:

使用 Google 可视化 api,有没有一种简单的方法可以查看 DataView 是否为空?

https://developers.google.com/chart/interactive/docs/reference#DataView

我可以看到也许使用 dataView.getValue(0, 1) 等来检查空值,但它也包含列标题。

我猜这很棘手,因为数据视图可能有许多不同的格式,但有没有一种通用的方法来检查空数据视图?我正在将数据视图用于饼图。

【问题讨论】:

    标签: google-visualization dataview


    【解决方案1】:

    如果我没记错的话,这个方法很容易做到

    var predata = response.getDataTable();
    var vals = new Array();
    var rownum = predata.getNumberOfRows();
    // Make sure our data isn't empty.
    if (null==predata) // yoda was here
    return;
    

    返回数据源返回的数据表。如果返回 null 查询执行失败,没有返回任何数据。

    【讨论】:

    • 感谢 Najzero,这可能只是因为我的数据表中仍然包含数据,但它为空。可能只是我的数据构造奇怪。我正在使用记录集生成我的数据服务器端,因此如果行没有数据,则插入空值。也许我的案例是一个边缘案例,所以为什么我发现很难将 API 与它一起使用。
    【解决方案2】:

    通过阅读文档,您似乎正在寻找 dataView.getNumberOfRows()。但是,在调用它之前,您需要获取过滤后的空行,然后将它们隐藏起来。这是an example 使用Google Code Playground,我在其中检查一列是否为null,然后如果该行为null,则隐藏该行。将该示例的 Google Code 的默认 JavaScript 替换为以下内容:

    function drawVisualization() {
      var dataTable = google.visualization.arrayToDataTable([
        ['Name',   'Age', 'Instrument', 'Color'],
        [null,   null,     null,    null],
        ['Paul',   52,     'Sitar',     'Red'],
        ['George', 16,     'Guitar',    'Green'],
        ['Ringo',  72,     'Drums',     'White']
      ]);
    
      var table = new google.visualization.Table(document.getElementById('table'));
      table.draw(dataTable, null);
    
      var dataView = new google.visualization.DataView(dataTable);
    
      // Get rows where the 2nd column contains null
      var filteredRows = dataView.getFilteredRows([{column: 1, value:null}]); 
      console.log(filteredRows);
    
      dataView.setColumns([0, 1]);
    
      // Hide the filtered rows returned
      dataView.hideRows(filteredRows);
    
      // Check the number of rows that now exist
      console.log(dataView.getNumberOfRows());
    
      var chart = new google.visualization.ColumnChart(document.getElementById('chart'));
      chart.draw(dataView, {width: 400, height: 200});
    }
    

    【讨论】:

    • 谢谢Jacob,我试过没有用,因为即使行是空的,它仍然会返回行数。这可能只是我在服务器端构建数据表 json 的方式。
    • @Alex Key 我已经用一个可能对您有用的示例更新了我的答案。我认为您需要先使用 getFilteredRows 来检查是否为空,然后隐藏为空的行。
    【解决方案3】:

    getDistinctValues 可以帮助你。当应用于沿 Y 轴可视化的列时,它适用于折线图。

    【讨论】:

    • 谢谢,我已经为您的回答 +1,但必须承认我的问题来自 2013 年的前世,因此无法对其进行测试。但感谢您的帮助。如果证明对其他人有用,我会让版主将其标记为答案!
    【解决方案4】:

    好像不太对劲……

    也许我应该在客户端甚至看到数据之前在服务器端将 null 替换为 0....

    我已经采取了:

    if (dataView.getValue(0, 1) === null || dataView.getValue(1, 1) === null || dataView.getValue(2, 1)) === null)
    

    我的数据视图结构在哪里:

    列标题 1 |数据 栏目 2 |数据 专栏标题 3 |数据

    【讨论】:

    • null 通常表示“无数据”,而 0(零)是有效的数值(在大多数情况下有意义),因此将 null 替换为 0(零)是不可接受的常见场景中的选项...
    猜你喜欢
    • 1970-01-01
    • 2011-12-28
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多