Ask Your Question
2

How can a datatable have a changing column header based on a JSON array?

asked 2021-10-03 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-08-30 04:00:00 +0000

woof gravatar image

To have a changing column header based on a JSON array, you can follow these steps:

  1. Parse the JSON array using JavaScript, and retrieve the column names as an array.

  2. Create a DataTable object and initialize it with an empty data array.

  3. Create a loop to iterate over the array of column names, and create column definitions for each column.

  4. Add the column definitions to the DataTable object using the addColumn() method.

  5. 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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2021-10-03 11:00:00 +0000

Seen: 10 times

Last updated: Aug 30 '21