1

I have pretty clear object and map function in react js.

My data is in state variable this.state.response

response = [
    {
        "number": "CA1",
        "name": "Kiran",
        "type": "Books",
        "contact": "98989898"
    },
    {
        "number": "CA2",
        "name": "Rahul",
        "type": "MP3",
        "contact": "98989898"
    }
]  

& Here I want to print data in table in react jsx file

{
    this.state.response !== "" &&
    this.state.response.map((data, i) => (
        <tr key={i}>
            <td>{i+1}</td>
            {
                console.log("Here I want to print data");
            }
            <td></td>
        </tr>
    ))
}

I can access each data with {data.number} or {data.name}

But I dont know the keys like number, name or type in the response which is dynamic data from API.

So my question is how can I create multiple with data value from response.

4 Answers 4

3

Object.entries will return all the properties and values as keys and values in array, Object.keys will return all the properties in array and Object.values will return all the values in array

this.state.response.map((data, i) => (
        <tr key={i}>
            <td>{i+1}</td>
            {
                console.log(Object.entries(data));
                Object.values(data).map(d => <td>{d}</td>);
            }
            <td></td>
        </tr>
Sign up to request clarification or add additional context in comments.

2 Comments

Is there any code to directly show field values in <td> ? Thank you for your response btw
Yup, I updated the code, this will show values only.
1

Use method Object.keys() to get an array of keys in the given object

{
    this.state.response !== "" &&
    this.state.response.map((data, i) => (
        <tr key={i}>
            <td>{i+1}</td>
            {
                Object.keys(data) //Returns array of all keys: Array ["number", "name", "type", "contact"]
            }
            <td></td>
        </tr>
    ))
}

1 Comment

I am trying to complete my requirements, will let you know. Thanks
1

Object.values will loop through the number of values in the data and show them in td tag

this.state.response.map((data, i) => (
    <tr key={i}>
       <td>{i+1}</td>
       {Object.values(data).map(val => {
             return <td>{val}</td>;
           })
        }
    </tr>
));

To get the keys along with the values you'll have to use Object.entries.

    this.state.response.map((data, i) => (
        <tr key={i}>
           <td>{i+1}</td>
           {Object.entries(data).map(val => {
             return <div>
               <td>{val[0]}</td><td>{val[1]}</td>
               <br />
             </div>
               })
            }
        </tr>
    ))

Comments

1

You can get the keys from an object using Object.keys(object). After that you can loop through the keys and access each key on each object.

class ResponseTable extends React.Component {
  state = { 
    response: [{
      "number": "CA1",
      "name": "Kiran",
      "type": "Books",
      "contact": "98989898"
    }, {
      "number": "CA2",
      "name": "Rahul",
      "type": "MP3",
      "contact": "98989898"
    }]
  };
  
  render() {
    const keys = Object.keys(this.state.response[0]);
  
    return (
      <table>
        <thead>
          <tr>{keys.map(key => <th key={key}>{key}</th>)}</tr>
        </thead>
        <tbody>
          {this.state.response.map((item, index) => (
            <tr key={index}>
              {keys.map(key => <td key={key}>{item[key]}</td>)}
            </tr>
          ))}
        </tbody>
      </table>
    );
  }
}

ReactDOM.render(
  <ResponseTable />,
  document.querySelector("#response-table-container")
);
<script src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<div id="response-table-container"></div>

Note that this solution uses this.state.response[0] to determine the keys. If this array can be empty you might need to set up some sort of default, because this.state.response[0] will evaluate to undefined.

In this scenario one solution would be use an empty object as default:

Object.keys(this.state.response[0] || {})

Which will return an empty array if response is empty. But you could also render an message notifying the user of the empty results.

if (this.state.response.length == 0) {
  return <div>Nothing found</div>;
}

These are just examples and you'll have to determine yourself what you want to do in such a scenario. If this scenario never occurs you don't have to handle it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.