-1

This may be a really daft question or an impossible question..

I have a table which uses two arrays of objects like so:

const columnData = [
  { id: 'name', label: 'Name' },
  { id: 'value', label: 'Value' }
];

const rowData = [
  { name: 'Name 01', value: 100 },
  { name: 'Name 02', value: 150 },
  { name: 'Name 03', value: 200 },
];

I am writing this as a separate react component so I can reuse it and just change the two sets of data passed in as props. This is all fine and working, however I am struggling to figure out how to map the rows and columns to be dynamic.

i.e.:

...
{this.props.rowData.map(row => {
  return (
    <tr>
    {this.props.columnData.map(column => {
      return (
        <td>{row.(THE_COLUMN_ID_TO_GET_THE_VALUE)}</td>
      );
    }
    </tr>
  );
}
...

I hope I make some sense here as it's a bit vague.. I basically want to get the value from rowData using the column id name. EG: <td>{row.name}</td><td>{row.value}</td> without hardcoding the item.

Timmo
  • 2,266
  • 4
  • 34
  • 54

2 Answers2

3

You can use the [] syntax on objects to obtain values based on computed properties.

{this.props.rowData.map(row => {
 return (
   <tr>
     {this.props.columnData.map(column => {
       return (
        <td>{row[column.id]}</td>
       );
     }
   </tr>
 );
}
Joseph Ditton
  • 998
  • 8
  • 7
1

So you just want to get the property of the row that matches the column id? You can access a property with dynamic name using square brackets like row[column.id]

{this.props.rowData.map(row => {
  return (
    <tr>
    {this.props.columnData.map(column => {
      return (
        <td>{row[column.id]}</td>
      );
    }
    </tr>
  );
}
gafi
  • 12,113
  • 2
  • 30
  • 32