Building a dynamic table with D3.js using undisclosed JSON information

I am attempting to generate a table using D3.js along with a JSON file.

The dataset comprises six columns: code, name, unit, value, target, and norm. The objective is to display only three of them (name, target, and value) in the table. My intention is to utilize the values from the [code] and [norm] columns to define the "id" and the "class".

Below is the foundational code that I am employing. This code effectively creates the table itself but encounters issues when it comes to identifying "id" and "class":

  var data = [{
    "code": 100,
    "name": "A",
    "unit": 12,
    "value": 0.6,
    "target": 0.75,
    "norm": "alert"
  }, {
    "code": 106,
    "name": "B",
    "unit": 12,
    "value": 0.6,
    "target": 0.75,
    "norm": "danger"
  }, {
    "code": 112,
    "name": "C",
    "unit": 12,
    "value": 0.9,
    "target": 0.75,
    "norm": "ok"
  }];

  var columns = ['name', 'target', 'value'];
  var table1 = d3.select('#table').append('table');

  var thead = table1.append('thead');
  var tbody = table1.append('tbody');

  // adding the header row
  thead.append('tr')
    .selectAll('th')
    .data(["Name", "Target", "Value"])
    .enter()
    .append('th')
    .text(function(column) {
      return column;
    });

  // generate a row for each object in the data
  var rows = tbody.selectAll('tr')
    .data(data)
    .enter()
    .append('tr');

  // create a cell for each column in every row
  var cells = rows.selectAll('td')
    .data(function(row) {
      return columns.map(function(column) {
        return {
          column: column,
          value: row[column]
        };
      });
    })
    .enter()
    .append('td')
    .html(function(d) {
      return d.value;
    });

});

My intended output for the table structure is provided below, where the JSON attributes of [code] are utilized as the "id" and [norm] serves as the "class". I have faced challenges in utilizing data elements at the cell level that are not used for populating the table's data fields. How can this be achieved?

<div id="table">
  <table>
    <thead>
      <tr>
        <th>Name</th>
        <th>Target</th>
        <th>Value</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td id="100" class="alert">A</td>
        <td>0.75</td>
        <td>0.6</td>
      </tr>
      <tr>
        <td id="106" class="danger">B</td>
        <td>0.75</td>
        <td>0.6</td>
      </tr>
      <tr>
        <td id="112" class="ok">C</td>
        <td>0.75</td>
        <td>0.9</td>
      </tr>
    </tbody>
  </table>
</div>

Answer №1

When working with the td columns mapping, consider adding additional keys such as id and class:

For example:

var columns = ['name', 'target', 'value'], column_id = 'code', column_class = 'norm';
 ....
 ....

return columns.map(function(column) {
            return {
              column: column,
              value: row[column],
              id: row[column_id],
              class: row[column_class]
            };
          });

Then, apply it to the td elements like this:

.attr('id', function(d) { return d.column === 'name' ? d.id : null; })
.attr('class', function(d) { return d.column === 'name' ? d.class : null; })

Here's a concise code snippet incorporating the above:

 var data = [{
    "code": 100,
    "name": "A",
    "unit": 12,
    "value": 0.6,
    "target": 0.75,
    "norm": "alert"
  }, {
    "code": 106,
    "name": "B",
    "unit": 12,
    "value": 0.6,
    "target": 0.75,
    "norm": "danger"
  }, {
    "code": 112,
    "name": "C",
    "unit": 12,
    "value": 0.9,
    "target": 0.75,
    "norm": "ok"
  }];

  var columns = ['name', 'target', 'value'], column_id = 'code', column_class = 'norm';
  var table1 = d3.select('#table').append('table');

  var thead = table1.append('thead');
  var tbody = table1.append('tbody');

  // Add header row
  thead.append('tr')
    .selectAll('th')
    .data(["Name", "Target", "Value"])
    .enter()
    .append('th')
    .text(function(column) {
      return column;
    });

  // Create rows for each object in the data
  var rows = tbody.selectAll('tr')
    .data(data)
    .enter()
    .append('tr');

  // Generate cells for each row and column
  var cells = rows.selectAll('td')
    .data(function(row) {
      return columns.map(function(column) {
        return {
          column: column,
          value: row[column],
          id: row[column_id],
          class: row[column_class]
        };
      });
    })
    .enter()
    .append('td')
    .attr('id', function(d) { return d.column === 'name' ? d.id : null; })
    .attr('class', function(d) { return d.column === 'name' ? d.class : null; })
    .html(function(d) {
      return d.value;
    });
<script src="https://d3js.org/d3.v4.min.js"></script>


<div id="table">

</div>

I trust this information is useful. :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Backbone sorting is specifically designed for organizing views within the framework

As I work on creating a sorting function in backbone, I have come across recommendations to use views to listen for changes in collections and then render the views once the collections are sorted. However, this approach does not suit my needs for two main ...

show the day of the week for a specific date saved in a MongoDB database

I need to create a report showing the total number of purchases for each day in the past week, formatted like this: { "sunday":30, "monday":20, ... } Each purchase in the database is structured as follows: { _id: 603fcb ...

The double click feature is not functioning properly when used in conjunction with the selectpicker Boostrap

<select class= "selectpicker" id="cus_id"> <option value="654" >test1</option> <option value="6877" >test2</option> <option value="8687" >test3</option> </select ...

Struggling to create an access token with the Slack API

My goal is to retrieve an access token from the Slack API. When I use the code provided below, it generates an authorization URL containing a temporary code in the query string. Once permissions are granted, the process redirects to /slack/oauthcallback. ...

Tips for iterating through a JSON object's values with jQuery AJAX

Is there a way to iterate through the json data with HTML content fetched from an ajax call in Jquery? For instance, I want to calculate the number of li tags within the provided data that have a specific class. I am looking to count the number of li tags ...

The `res.download(filepath)` function seems to be failing to initiate a download request on the user's

I'm currently working on a project involving image compression using node and react. The issue I'm facing is that when the server sends the image to the client using res.download(filepath), the download doesn't trigger on the client side. Ho ...

I am currently utilizing a custom database connection class in node.js and ES6, however, the value being returned is showing as 'undefined'

Upon reviewing the other question, I realized that it may address a similar issue. However, I am struggling to apply the provided solution in his function `foo(){..}` to my specific problem, especially since his code is written in jQuery. Can someone pleas ...

The connection between socket.emit and socket.on is currently disrupted

When I was integrating a chat page into my current express app using socket.io, I encountered an issue. var io = socket(server); io.on('connection', (socket) => { console.log('made socket connection', socket.id); // Handle c ...

What is the best way to switch between three different menus and ensure that the last selected menu remains open when navigating to a new page

My knowledge of javascript, jquery, and php is pretty much non-existent, unfortunately. I only have a grasp on html and css at the moment. However, I will be starting school to learn these languages in the fall! The issue I am currently facing is creating ...

Nightwatch encounters issues during the initialization of the page object

I am currently in the process of testing a Vue application. I have developed 2 simple page objects and created 2 simple spec files to run the end-to-end test. The first test (login) passes without any issues, however, the second test fails with the followi ...

I encountered an issue after updating data with ajax where a property in a bootstrap button went missing, causing a modal to malfunction

Currently, I am working on a project using Django and for handling Ajax calls, I have been referring to this project: https://pypi.org/project/django-bootstrap-modal-forms/ In my project, there is a table where by clicking the Ver Tratamiento button, I ca ...

Conceal the "contact numbers stored in the phonebook" on the page while still showing the outcomes

Here is a straightforward Live Search script that I find to be quite handy, but I am looking to make a specific modification. https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_filter_list The current script uses live search for a "phonebook", ...

Utilizing a PHP Class object in Javascript by accessing its properties within a Javascript function

I'm struggling to access the attributes of an object within a JavaScript function that I created. This object was originally a PHP object that I converted to JSON using json_encode() In my project, there is 1 PHP file and 1 external JS file. In the ...

Avoid using the 'exports' keyword when compiling in Typescript

I recently started learning Typescript, although I am proficient in JS. My inquiry pertains to utilizing modules in TS for coding purposes and then excluding the modules when converting to JS. In traditional JS, I segment functionalities into different fi ...

"Exploring the realms of AngularJS through callback functions and variable scopes

I am currently experiencing an issue with JavaScript in general. Specifically, I am trying to update a list after invoking a callback from two separate files. Here is the description of the callback : this.modify = function(){ var self = this; v ...

Is it possible to transform a virtual DOM into a tangible DOM element without triggering a render?

Currently, I am utilizing html2canvas to capture a screenshot of my webpage. The challenge I am encountering is that html2canvas requires an element as a parameter. In my case, I am working with a React app where I use a template to access the virtual DOMs ...

Improve the parallax effect in your React component

Do you have any tips on smoothing out the scrolling animation for a React component with a simple parallax effect? I tried using requestAnimationFrame() in vanilla JS, but it doesn't seem to work well within the React component's rendering cycle. ...

What is the best way to restrict users from inputting anything other than alphabetic characters in an HTML text input field

I'm trying to create a text input field that will only accept one letter from A to Z (not case sensitive). I've managed to limit the input to one character using the maxlength attribute, but users can still enter numbers or special characters. &l ...

Discovering the selected div in Angular is a common task that can be

I am looking to determine which div is currently selected. Please review my code: <divdsadsadasda toggle(i) { console.log(i) // the index has been obtained } I am trying to identify the selected div and retrieve values from the clicked item. ...

Getting specific information from a JSON URL can be achieved by utilizing tools like JavaScript

Looking for a solution to extract specific data from JSON file? Here is the JSON Data available in PHP url named house.php: { "Error": "", "ErrorCode": 0, "Guid": "", "Id": 0, "Success": true, "Value": [ { "MAIN": 225, "PHASE": 219418523, "G": "7TH Divisi ...