0

I currently have a functional component table that takes two props, data which is an array of stock price data, such as: [{symbol:'TSLA',price:'420'},{symbol:'PLTR',price:'9000'}], and headers, which is simply a dynamically created array of all of the keys in the data, which would be [symbol,price] for the data above.

As of now, I have a functioning table, however I am having issues maping the headers to each individual stock object. Here is the code I have now:

          <TableBody>
            {props.data.map((dataElement) => (
              <TableRow key={dataElement.symbol}>
                <TableCell align="left">{dataElement.symbol}</TableCell>
                <TableCell align="left">{dataElement.price}</TableCell>
              </TableRow>
            ))}
          </TableBody>

but I would like to map each header to a tablecell that accesses the dataElement's properties for that header value. I was thinking it might be something like this, however THE FOLLOWING OBVIOUSLY DOES NOT WORK

   <TableBody>
    {props.data.map((dataElement) => (
      <TableRow key={dataElement.symbol}>
        {props.headers.map((header) => <TableCell>{dataElement.header}</TableCell>)}
      </TableRow>
    ))}
  </TableBody>

Does anyone know how I can achieve the functionality I am trying to achieve? Please let me know if clarification is needed.

JacobDClark
  • 77
  • 1
  • 1
  • 6

1 Answers1

0

dataElement.header will be undefiend in your example. You should use [] to use header value as a key of dataElement object. like below.

   <TableBody>
    {props.data.map((dataElement) => (
      <TableRow key={dataElement.symbol}>
        {props.headers.map((header) => <TableCell>{dataElement[header]}</TableCell>)}
      </TableRow>
    ))}
  </TableBody>
michael
  • 4,053
  • 2
  • 12
  • 31
  • This solution worked! Thank you so much! Any idea as to why the brackets worked when dot notation did not? – JacobDClark Nov 25 '20 at 18:56
  • This could be a good explanation - https://stackoverflow.com/questions/922544/using-variable-keys-to-access-values-in-javascript-objects If this worked, you can tick the answer. – michael Nov 25 '20 at 19:02