【问题标题】:How to render table from JSON array elemnts using d3如何使用 d3 从 JSON 数组元素呈现表格
【发布时间】:2014-10-01 06:51:01
【问题描述】:

伙计们,

我想使用 D3.js 为以下 JSON 呈现一个 html 表

我用于此过程的 JSON 在这里,http://jsfiddle.net/d9wgnbdd/2

例如,“办公室类型”有更多“代码”,而“代码”有更多“集群”,集群也有更多分支。

我想将表格显示如下,在此@mccannaff 中需要您的帮助。期待

Code   Office-code  Corp-Code  Region-Code  Cluster-Code
 CO     CRP           CBE       BN117        C1038
 CO     CRP           CBE       BN117        C1039
 CO     CRP           CBE       BN117        C1049
 CO     CRP           CBE       BN117        C1147

这是我要显示表格的 html,

    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
        <title>D3: Subselection Example</title>
        <script type="text/javascript" src="d3.js"></script>
        <style type="text/css">

        body {
          font: 13px sans-serif;
      }
      td, th {
        padding: 1px 25px 0px 1px;
        border: 1px black solid;
        width:80px;
    }   
    ul {
      list-style: none;
      font-weight: bold;
  }

  li {
      margin:  0.2em 0.0em;
      padding: 0.5em 1.0em;
      font-weight: normal;
  }

  </style>
  </head>
  <body>
  <script type="text/javascript">
    d3.json("Udashboard.json", function (error,data) {

    function tabulate(data, columns) {
      var table = d3.select('body').append('table')
      var thead = table.append('thead')
      var tbody = table.append('tbody');

    // append the header row
    thead.append('tr')
    .selectAll('th')
    .data(columns).enter()
    .append('th')
    .text(function (column) { return column.id; });

    // create a row for each object in the data
    var rows = tbody.selectAll('tr')
    .data(data.objects)
    .enter()
    .append('tr');

    // create a cell in each row for each column
    var cells = rows.selectAll('td')
    .data(function (row) {
        return columns.map(function (column) {
          return { column: column.id, value: eval('row.'+column.key) };
      });
    })
    .enter()
    .append('td')
    .text(function (d) { return d.value; });

    return table;
}

var columnFields = [ { id: "ID", key: "id" },
{ id: "Code", key: "officetype[0].code" },
{ id: "C_Code", key: "officetype[0].corp[0].code" },
{ id: "Name", key: "name" } ];

console.log (data);
// render the table(s) 
tabulate(data, columnFields); // 2 column table
});

    </script>

</body>
</html>

有人能帮我解决这个问题吗?

【问题讨论】:

  • 有人想对嵌套数组元素进行分组吗?
  • 对不起@Mary.Hansen,我看不到一种基于数组元素的分组方式,但也以如此复杂的方式嵌套。我建议你找到一种方法来展平这个 JSON 对象或将关键元素提取到更类似于表格的东西中,然后再问这个问题!
  • 我们可以渲染一个包含相同元素的 d3 表吗?不需要分组..我更新了我的问题——请看我现在简化的问题。希望你能帮忙。

标签: javascript d3.js multidimensional-array data-visualization crossfilter


【解决方案1】:

如果您只对代码感兴趣,您可以这样做(假设您的 HTML 中存在一个带有 &lt;tbody&gt; 的表,并且您的大 JSON 对象称为 data):

function codeOfInterest(keyString) {
    return ((keyString == "officetype") || (keyString == "corp") || (keyString == "region") || (keyString == "cpuster"));   
}

var fullList = [];

// Recurse into the data tree
function parse_object(obj, parent, parentLabel) {

    var type = $.type(obj);

    if (type == "object") {

        var parentParam = parent;

        // "code" is the only key we are interested in
        if ("code" in obj) {
           var label = (parentLabel == "" ? "code" : parentLabel + "_code");
           var newParent = $.extend({},parent);
           newParent[label] = obj["code"];
           parentParam = newParent; 
        } 

        // We have reached a leaf node, add to the list 
        if ($.isEmptyObject(obj)) {
            fullList.push($.extend({},parentParam));
        } else {
           for (var i in obj) {
              if ($.type(obj[i]) == "object" || $.type(obj[i]) == "array") {
                 if (codeOfInterest(i)) {
                    parse_object(obj[i], parentParam, i);
                 } else {
                    parse_object(obj[i], parentParam, parentLabel);
                 }
              }
           }
        }
    } else if (type == "array") {
        if ($.isEmptyObject(obj)) {

           // We have reached a leaf node (empty array), add to the list
           fullList.push($.extend({},parent));
        } else {
           for (var i in obj) {
               parse_object(obj[i], parent, parentLabel);
           } 
        }
    }
}

// Add the array of objects to a HTML table
function addToTable(dataList) {
   var defaultValue = "-";
   $.each(dataList, function(index,element) {
       // If one of the keys is undefined, replace its value with the default value
       var code = element.code === undefined ? defaultValue : element.code;
       var officetype_code = element.officetype_code === undefined ? defaultValue : element.officetype_code;
       var corp_code = element.corp_code === undefined ? defaultValue : element.corp_code;
       var region_code = element.region_code === undefined ? defaultValue : element.region_code;
       var cpuster_code = element.cpuster_code === undefined ? defaultValue : element.cpuster_code;

       // Add as a row to the table
       $("<tr><td>"+code+"</td><td>"+officetype_code+"</td><td>"+corp_code+"</td><td>"+region_code+"</td><td>"+cpuster_code+"</td></tr>").appendTo("tbody");
   });
}

$(function() { 
   parse_object(data.objects, {}, "");
   addToTable(fullList);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-07
    • 2018-11-18
    • 2019-08-08
    • 2023-04-04
    • 1970-01-01
    相关资源
    最近更新 更多