To have a changing column header based on a JSON array, you can follow these steps:
Parse the JSON array using JavaScript, and retrieve the column names as an array.
Create a DataTable object and initialize it with an empty data array.
Create a loop to iterate over the array of column names, and create column definitions for each column.
Add the column definitions to the DataTable object using the addColumn() method.
Finally, load the data into the DataTable object using the addRows() method.
Here is an example implementation in JavaScript:
// Sample JSON array
var data = [
{"name": "John", "age": 30, "gender": "male"},
{"name": "Jane", "age": 25, "gender": "female"},
{"name": "Bob", "age": 35, "gender": "male"}
];
// Retrieve column names as an array
var columnNames = Object.keys(data[0]);
// Create DataTable object
var dataTable = new google.visualization.DataTable();
// Define columns
for (var i = 0; i < columnNames.length; i++) {
dataTable.addColumn('string', columnNames[i]);
}
// Load data into DataTable object
for (var i = 0; i < data.length; i++) {
var row = [];
for (var j = 0; j < columnNames.length; j++) {
row.push(data[i][columnNames[j]]);
}
dataTable.addRows([row]);
}
// Render DataTable as a table
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(dataTable, {showRowNumber: true});
In this example, the column names are retrieved from the JSON array using the Object.keys() method. The DataTable object is then created, and column definitions are added to it using a loop. The data is loaded into the DataTable object using another loop, where each row is converted into an array of values using the column names. Finally, the DataTable is rendered as a table using the google.visualization.Table class.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-10-03 11:00:00 +0000
Seen: 10 times
Last updated: Aug 30 '21
What is the process for generating a dynamic subdomain/URL using vue.js?
How can the style of the loader be modified while the form submission is being processed?
I'm attempting to develop a Javascript-based comments section for my website.
What are some feasible methods to enable MIDI file playback on a web browser?
How can I resolve the issue of being unable to use Fetch to POST an array of Selected Checkboxes?
What is the method to hide the scroll button when reaching the bottom?
What is the process of using a custom nunjucks filter to filter collections in an eleventy template?
What is the method to create a dynamic checkbox using API data?
How can the user id from the login object be utilized in the resolvers after logging in?