Show information in a table based on a unique identifier

I am working with some data that looks like this

[
  {
   date: '20 Apr',
   maths: [70, 80.5, 100],
   science: [25, 20.1, 30]
  },
  {
   date: '21 Apr',
   maths: [64, 76, 80],
   science: [21, 25, 27]
  },
];

My goal is to present the data in a table format with customized labels for each subject. The desired output should look like this:

date   |      maths      |     science
       | min | val | max | min | val | max
20 Apr | 70  | 80.5| 100 | 25  | 20.1| 30
21 Apr | 64  | 76  | 80  | 21  | 25  | 27

I have attempted the code which can be viewed here. I am wondering if there is a way to achieve this desired output or if I need to restructure the data differently.

Answer №1

  • The initial structure includes two header rows, with the first header containing the "Date" cell.

  • Following that, create subject headers using the primary mark object and include subheadings such as "min", "val", and "max".

  • Subsequently, iterate over the subjects and populate the table body with relevant data.

const marks = [
  { date: "20 Apr", maths: [70, 80.5, 100], science: [25, 20.1, 30] },
  { date: "21 Apr", maths: [64, 76, 80], science: [21, 25, 27] },
];

const table = document.getElementById("table");
const tableBody = document.getElementById("table-body");
const tableHeader = document.getElementById("table-header");
const tableSubHeader = document.getElementById("table-sub-header");

if (marks[0]) {
  const { date, ...subs } = marks[0];
  Object.keys(subs).forEach((sub) => {
    const th = document.createElement("th");
    th.textContent = sub;
    th.setAttribute("colspan", 3);
    tableHeader.appendChild(th);
    ["min", "val", "max"].forEach((subheading) => {
      const th = document.createElement("th");
      th.textContent = subheading;
      th.setAttribute("scope", "col");
      tableSubHeader.appendChild(th);
    });
  });

}

marks.forEach((mark) => {
  const tr = document.createElement("tr");
  const { date, ...subs } = mark;
  const th = document.createElement("th");
  th.textContent = date;
  th.setAttribute("scope", "row");
  tr.appendChild(th);
  Object.keys(subs).forEach((sub) => {
    const [min, val, max] = subs[sub];
    tr.innerHTML += `<td>${min}</td><td>${val}</td><td>${max}</td>`;
  });
  tableBody.appendChild(tr);

});

body {
  font-family: arial;

}

table {
  table-layout: fixed;
  width: 100%;
  border-collapse: collapse;
}

td, th {
  padding: 0.5em;
  border: 1px solid black;
}

th {
  text-transform: capitalize;

}
<table id="table">
  <thead>
    <tr id="table-header"><th rowspan="2" scope="col">Date</th></tr>
    <tr id="table-sub-header"></tr>
  </thead>
  <tbody id="table-body">
  </tbody>
</table>

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

Jquery fails to function properly unless the page is refreshed

On my MVC page, I have implemented a feature where certain text-boxes are shown or hidden based on the value selected in a drop-down menu using jQuery. The functionality works fine when the page is isolated, but when placed under a menu, it encounters a pr ...

Transmit live video feed captured by getUserMedia to a Node.js server and then forward it to the Google Cloud Platform speech API

I am currently involved in a project that requires the use of the google-cloud-platform speech API. To achieve this, I am utilizing getUserMedia to acquire the MediaStream. However, I am unsure about what data I should be sending from it to the BackEnd. O ...

Could someone assist me in understanding why VScode is displaying an error stating it cannot locate a module?

node:internal/modules/cjs/loader:1051 throw err; ^ Error: The module '/Users/ben/Desktop/GA/unit2/week5/GA_Project_2/QuotaQuest/index.js' cannot be found. at Module._resolveFilename (node:internal/modules/cjs/loader:1048:15) at Modul ...

Create a versatile generic object using TypeScript

Looking to create a versatile onFilterChange helper function that works for all filters, eliminating the need to write it out separately each time. However, I've hit a snag: // helper.ts export function onFilterChange(prevState: Record<string, any& ...

Show/Hide Row in Material-UI DataGrid

I need assistance with expanding lines in Material UI. I am trying to create drop-down rows in my table (individually for each row) within a table built using Material UI. Despite researching extensively online, I have been unable to achieve consistent res ...

The error message "TypeError: Cannot read property 'map' of undefined when trying to set state as an array"

Encountering an error while trying to map the state for my posts:[] object: Error message: TypeError: this.state.posts.map is not a function While searching for a solution, I found something similar on this link, but unfortunately, it did not solve the ...

Extracting all usernames of members present in a specific voice channel and converting them into a string using Node.js on Discord

Hey everyone, I'm looking for a code snippet that will help me retrieve all the members from a specific voice channel by using its ID. I also need to extract and store the usernames of these members who are currently in that particular voice channel w ...

A web application using JavaScript and Node.js with a focus on creating a REST

After extensive research, I am eager to develop a web application using JavaScript and Node.js with an SQL back-end. However, the abundance of frameworks and tools available has left me feeling overwhelmed. While I have identified some that I would like to ...

Utilize an object model property as an array key for filtering in the AngularJS and MEANJS framework

I am currently working on a MEANJS application that includes a CRUD module for countries. When I select a country from the default list view, it redirects me to the view-country.client.view page. In order to enhance my model, I have introduced a field name ...

What methods are available to me for creating a wrapper for an Angular Component that simply changes the component selector name?

Having experience with React, you can simplify a library component in your app by giving it a new name like this: const MyAppTable = (props) => <LibraryTable ...props />; I'm interested in achieving a similar result in Angular, but I'm ...

Notification from HTML code within Django

In my Django project, I am trying to implement an alert. I am sending data from views.py to singup.html in order to display an alert based on certain conditions. However, initially the alert variable in HTML is not assigned a value. It is only after click ...

Inadequate termination of the while loop

I'm trying to generate a line of text in JavaScript running in Node, ensuring that it does not exceed a certain number of syllables. To achieve this, I have created a function utilizing the "syllable" library as follows: function generateLine(maxSyll ...

Different techniques for using percentages in CSS transformations to create dynamic animations for DOM element translations

I have 14 objects positioned across the dom that I need to animate using the translate property. Currently, I am using transform: translate(x%, y%) for each object, requiring me to calculate the translation amount and apply a CSS style individually. This m ...

Guide on Retrieving the Current URL in NodeJS

Currently, I am utilizing express in conjunction with node.js. In my setup, the following code is present: app.get('/callback', async function (req, res) { Whenever a user reaches the callback section of my website, I expect to receive the req ...

The template literal expression is being flagged as an "Invalid type" because it includes both string and undefined values, despite my cautious use of

I am facing an issue with a simple component that loops out buttons. During the TypeScript build, I encountered an error when calling this loop: 17:60 Error: Invalid type "string | undefined" of template literal expression. In my JSX return, I ...

Using React Higher Order Components with several different components

Is it possible to create a React HOC that can accept two components instead of just one wrapped component and toggle between them? For instance, in the code snippet below, rather than having <h3>component one</h3> and <h3>component two< ...

Enhance LCP Performance in Next.js for Faster Loading Speeds

I'm currently working on a next.js project (version 11.1.2) and my goal is to improve the page speed performance. To track this, I am using Google PageSpeed Insight for evaluation. Presently, the scores stand at: 40-50 for mobile (!!) 80-90 for deskt ...

Issues with basic emit and listener in socket.io

I recently inherited an App that already has socket IO functioning for various events. The App is a game where pieces are moved on a board and moves are recorded using notation. My task is to work on the notation feature. However, I am facing issues while ...

Bidirectional enumeration in TypeScript

I am working with an enum defined as: enum MyEnum { key1 = 'val1' key2 = 'val2' } However, I am unsure how to create a SomeType implementation that fulfills the following requirements: Function: const myFunction = (param: SomeT ...

conceal the "load more" option when no additional content is available for loading

I recently incorporated a "load more" button using the plugin called "easy load more" (https://wordpress.org/plugins/easy-load-more/). While the button is functioning well, it continues to appear even when there are no more posts to display. I am seeking s ...