adinutzyc21 adinutzyc21 - 8 months ago 49
React JSX Question

Table Data Structure Design

I am trying to create a data structure to hold a dynamic table in React. Currently, I'm holding my data as

{item00: "data 0", item01: "data 1", item02: "data 2"},
{item10: "data 3", item11: "data 4", item12: "data 5"},
{item20: "data 6", item21: "data 7", item22: "data 8"}

and adding a new row would mean appending a

{item30: "data 9", item31: "data 10", item32: "data 11"}

and adding a new column would mean inserting
at the end of each row.

My question is, is there any better data structure I could use? I'm having trouble with coming up with something that would make inserting new columns easy.

Also, how would I keep a counter of the columns I am adding / deleting? I'm sure there are specific ways of doing that, but I'm having trouble coming up with appropriate search terms..

Answer Source

You can consider this,

Make each element inside the Array as a row.


[{}, {}, {}, {}] //each {} is a row

Make each element inside the Object as a column,


  {name: "xyz", age: "21", location: "india"}, //this will be a row
  //name, age, location will be columns

New row can be appended inside the Array with the same or additional columns.


Original Data

var t = [ {name: "xyz", age: "21", location: "india"}, ]

Adding new Data

t.push({name: 'abc', age: '44', location: 'india', phone: 56654345})

Rendered table will be

Name     Age     Location   Phone
xyz    | 21   |  india    |   
abc    | 44   |  india    |  56654345

Hope this helps!