How to render data to a table/best way to store data for table rendering

So I currently have data stored as tableData like so…

export default {
name: “TableView”,
data() {
return {
numberOfRows: 10,
tableData: [
{
header: “Human”,
columns: [
{
columnName: “Sam”,
cellValues: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
},
{
columnName: “Foo”,
cellValues: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
},
{
columnName: “Bar”,
cellValues: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
},
],
},
{
header: “Dog”,
columns: [
{
columnName: “Yoda”,
cellValues: [1, 2, 3, 4, 5, 6, 7, 8, 9, 12],
},
{
columnName: “Pinky”,
cellValues: [1, 2, 3, 4, 5, 6, 7, 8, 9, 13],
},
],
},
],
};
},
};

What I essentially want to render is something along the lines of this https://jsfiddle.net/s2up60rn/15/

For the life of me I can’t come up with a good solution with v-for etc. I’m not sure if its how I am storing my data is incorrect.

When working with tables and loops you have to think in terms of row by row. This can make it less friendly to read as a data model.

headings: ['Human', 'Dog'],
subHeadings: ['Sam', 'Food', 'Bar', 'Yoda', 'Pinky']
data: [
  [1,1,1,1,1],
  [2,2,2,2,1],
  // etc.
]

But as you can see, this isn’t very flexible. How would you handle the colspans?

headings: [{ label: 'Human', colspan: 3 }, { label: 'Dog', colspan: 2 }],
subHeadings: ['Sam', 'Food', 'Bar', 'Yoda', 'Pinky']
data: [
  [1,1,1,1,1],
  [2,2,2,2,1],
  // etc.
]

Is a possible solution. So now you’re essentially mapping the data model in the same fashion as the DOM tree.

1 Like

Hmm ok, the reason I wanted to have it in one state instead of breaking it up into multiple states was that now whenever I make some manipulation in the table (e.g remove a heading, where it then removes its subheadings and correlated data) I have to keep in mind headings, subHeadings and data, this can lead to me/another dev forgetting to update one of the states which may break the table. Where if I have one state solution I would only have to remove the heading inside of that state and it would take care of the rest.

Thank you regardless, I will add comments into the code so users are aware to update accordingly.

You could try deriving the final state from individual objects. So something similar to your first data model, but the derived state is in a final form (such as my example) that makes it easy to loop over as table data.