Home > Software engineering >  Using a Response to create a table React JS dynamically
Using a Response to create a table React JS dynamically

Time:11-23

I am currently getting a response that returns an array like this

 const response = [{
    time: 1,
    speed: 2,
    direction:3,
    image:'url'

    
  },{
    time: 1,
    speed: 2,
    direction:3,
image:'url'
  },{
    time: 1,
    speed: 2,
    direction:3,
    image:'url'
    
  },{
    time: 1,
    speed: 2,
    direction:3,
image:'url' 
  }]

How do I make a table which the first column contains only the names of the properties. then subsequent columns contain the data from the response respectively using the image URL as a header I have never used tables in JS before. It also needs to be dynamic so that any number of of results from the response can be generated with any number of keys from the object as all objects in the array will have the same keys

Ideally I want the table to look like this I know it is simple but it is really frustrating so any help would be appreciated

            image           image           image 
time          1               1               1 
speed         2               2               2
direction     3               3               3

CodePudding user response:

Not sure if this is what you want. You can iterate over the keys and values of the object.

  <table>
    <thead>
      <tr>
        <td />
        {response.map((el) => (
          <td>{el.image}</td>
        ))}
      </tr>
    </thead>
    <tbody>
      {Object.keys(response[0])
        .filter((k) => k !== "image")
        .map((k) => (
          <tr>
            <td>{k}</td>
            {response.map((r) => (
              <td>{r[k]}</td>
            ))}
          </tr>
        ))}
    </tbody>
  </table>
  • Related