2015-09-24 48 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>