1

I want to display the dynamic key and its value in a table using reactjs

Actual EC: "2.5"
Actual pH: "6"
location: "Substrate"

Above is the data from API. There is Actual EC and Actual PH. But in table i want to display like this

EC:2.5
ph:6

How to display ? I have stored those API data in state like this:

this.setState({
   prod_dashboard: data.params
})

Here is the render:

    {this.state.prod_dashboard && this.state.prod_dashboard.map((st, i) => (
       <Col lg="3" key={i}>
         <Card className="task-box" style={{ backgroundColor: 'black' }}>
           <CardBody>
             <div className="table-responsive">
               <table className="table-nowrap mb-0" style={{ color: "yellow" }}>
                 <tbody>
                      <tr>
                      {st.location !== "" ?
                       <th scope="row">{st.location} :</th>
                           :""}
                       <td style={{ paddingLeft: "20px" }}>{st["Actual EC"]}</td>
                       </tr>

                 </tbody>
                </table>
              </div>
           </CardBody>
         </Card>
      </Col>
   ))}
Nithish
  • 5,393
  • 2
  • 9
  • 24
Karthik
  • 47
  • 3
  • What are you trying to achieve? Do you simply need to convert your values to numbers once inside the table? If so, just wrap your value inside `Number()` as `Number(st["Actual EC"])` – ale917k Mar 22 '21 at 06:44
  • I need to validate the key first. If the key contains the word "Actual" then i need to remove that word and display the following word. – Karthik Mar 22 '21 at 06:53
  • In this case , i have "Actual EC",so i need to remove "Actual" and display only "EC" – Karthik Mar 22 '21 at 06:53
  • See how to rename obj keys here https://stackoverflow.com/a/14592469/11895568 – ale917k Mar 22 '21 at 07:31
  • What's the data type of `Actual EC: "2.5" Actual pH: "6" location: "Substrate"`? Object or Array? – Ajeet Shah Mar 22 '21 at 08:05

1 Answers1

0

Based on the understanding that you want to remove "actual" from the key part. if the object format is fixed and going to be like i.e. "Actual EC" You can parse you object and form new one which will not contain "Actual" in key part and use newly formed object in render. Please refer code below.

var obj = {"Actual EC": "2.5",
"Actual pH": "6",
"location": "Substrate"};

var massageObj = {};
Object.keys(obj).map((key) => {
  key.indexOf('Actual') != -1 ? massageObj[key.split(" ")[1]] = obj[key] : 
  massageObj[key]=obj[key]
})
Prashant
  • 375
  • 2
  • 8