D3 Ordering Column Rule Based On JSON Response
I have this d3 function that generates a table based on my data's JSON output function tabulate(data, columns) { $('body').css('padding-top', '10px') var table = d3.select('#respon
Solution 1:
It looks like you're passing an array columns
to your tabulate
function based on which you organize your data before populating your rows. Where are you getting this from?
Based on your comment, the values in the columns
array are dynamic and can include anything. What we can do here is look for the count
header, remove it and then add it to the end. This way, we have our headers the way we want it and the table is generated accordingly. Check the snippet below:
var data = [{
"Cars": "Mercedes",
"Count": 281,
"Type": "Automatic"
}, {
"Cars": "Toyota",
"Count": 1929,
"Type": "Manuel"
}];
// case where count is in the middle
var columns = ["Cars", "Count", "Type"];
// some basic array manipulation to remove it from the middle and put it in the end
var position = columns.indexOf("Count");
if(position != -1) {columns.splice(position, 1);}
columns.push("Count");
function tabulate(data, columns) {
//$("body").css("padding-top", "10px")
var table = d3.select('#response').append('table').attr('class', 'table table-bordered table-hover')
var thead = table.append('thead')
var tbody = table.append('tbody');
thead.append("tr")
.selectAll("th")
.data(columns).enter()
.append("th")
.text(function(column) {
return column;
});
var rows = tbody.selectAll('tr')
.data(data)
.enter()
.append('tr');
console.log("rows: " + rows)
var cells = rows.selectAll('td')
.data(function(row) {
return columns.map(function(column) {
return {
column: column,
value: row[column]
};
});
})
.enter()
.append('td')
.text(function(d) {
return d.value;
});
return table;
}
tabulate(data, columns);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="response">
</div>
Post a Comment for "D3 Ordering Column Rule Based On JSON Response"