0

I want to have multiple rows for one data set using HTML table.

var row = 0;

var test = [{
  food: "A",
  grade: ["1", "2", "3", "5"]
},
{
  food: "B",
  grade: ["1", "2"]
},
{
  food: "C",
  grade: ["1"]
},]

var display = document.getElementById("table-body");

var newRow = display.insertRow(row);

var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);

cell1.innerHTML = test[0]["food"]
cell2.innerHTML = test[0]["grade"]
For example:
Food || Grade
---------------
A       || 1
        || 2
        || 3
        || 5
---------------
B.     || 1
       || 2
---------------
C.     || 1

However, I'm only able to have them all listed in one cell i.e. (1,2,3,5). Any ideas on how to replicate the table above?

rickandmorty
  • 165
  • 2
  • 8
  • Familiarize yourself with [how to access and process nested objects, arrays or JSON](https://stackoverflow.com/q/11922383/4642212) and how to [create objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) and use the available [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods) methods (both static and on prototype). – Sebastian Simon Apr 06 '21 at 00:54

1 Answers1

1

Use nested loops to add rows for each task. Use the rowspan attribute in the first column to make it fill expand to all the rows for that device's tasks.

test.forEach(t => {
    t.tasks.forEach((task, i) => {
        let newRow = display.insertRow();
        if (i == 0) {
            let firstCell = newRow.insertCell();
            firstCell.innerText = t.device;
            firstCell.setAttribute('rowspan', t.tasks.length;
        }
        newRow.insertCell().innerText = task;
    });
});
Barmar
  • 741,623
  • 53
  • 500
  • 612