2015-09-24 47 views
2

我的数据是低于JSON对象JSON数组 -在D3中创建表和JSON对象

var data = [{id: 0, reflexive: false}] 

我想说明这些属性的表与主要作为在第一款TD和值标签第二个td中的输入框。 所以对于上面的数据我想要两行。第一个td值的第一行应该是id,第二个td值应该是0.同样在第二行,第一个td值应该是自反的,第二个td值应该是false。

下面是我现在已经实施的代码 -

var table = d3.select("body").append("table") 
     .attr("style", "margin-left: 250px; border: 2px"), 
    thead = table.append("thead"), 
    tbody = table.append("tbody"); 

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

// create a row for each object in the data 
var rows = tbody.selectAll("tr") 
    .data(data[0].keys().length()) 
    .enter() 
    .append("tr"); 

    var cells = rows.selectAll("td") 
    .data(function(row) { 
     return columns.map(function(column) { 
      return {column: column, value: row[column]}; 
     }); 
    }) 
    .enter() 
    .append("td") 
.append("input") 
.attr('disabled', null) 
.attr("name", "byName") 
.attr("type", "text") 
.attr("value",function(d) { return d.value; }) 

return table; 

但它作为一个单行键作为TD标题和值给出输出。任何建议都会有所帮助。

+0

什么是列?发布你的整个代码。 – somename

+0

我的列是静态文本值为 - var columns = [“Property Name”,“Property Value”]; –

+0

为什么你有这样的数据var ary = [{id:0,reflexive:false}]; 不应该是 _var ary = {id:0,reflexive:false,moreKey:someValue}; _我的意思是说它是一个json数组,但只是一个带有一些关键值的json对象。 – Cyril

回答

1

我也认为这个数据是这样的,而不是在您的示例阵列的上述

var ob = {id: 0, reflexive: false}; 

你需要使这个键值的数组是这样的:

data = Object.keys(ob).map(function(k) { return {key:k, value:ob[k]} }) 

现在做表和TR和TDS取决于数据象下面这样:

var ob = {id: 0, reflexive: false}; 
 

 
data = Object.keys(ob).map(function(k) { return {key:k, value:ob[k]} }) 
 

 

 
var table = d3.select("body").append("table") 
 
     .attr("style", "margin-left: 50px; border: 2px"), 
 
    thead = table.append("thead"), 
 
    tbody = table.append("tbody"); 
 

 
// append the header row 
 
thead.append("tr") 
 
    .selectAll("th") 
 
    .data(["Property Name", "Property Value"]) 
 
    .enter() 
 
    .append("th") 
 
     .text(function(d) { console.log(d);return d; }); 
 

 

 
// create a row for each object in the data 
 
var rows = tbody.selectAll("tr") 
 
    .data(data) 
 
    .enter() 
 
    .append("tr"); 
 
    ///add the key in first td 
 
    rows.append("td") 
 
\t .text(function(d) { ;return d.key; }); 
 
\t ///add the value in second td 
 
    rows 
 
    .append("td") 
 
\t .append("input") 
 
\t .attr('readonly', true) 
 
\t .attr("name", "byName") 
 
\t .attr("type", "text") 
 
\t .attr("value",function(d) { return d.value; });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>