javascript - How to get value without knowing key in map function of react js - Stack Overflow

I have pretty clear object and map function in react js.My data is in state variable this.state.respon

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.

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.

Share Improve this question asked Jun 18, 2021 at 11:47 Kirankumar DafdaKirankumar Dafda 2,3845 gold badges31 silver badges59 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 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>

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>
    ))
}

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>
    ))

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./react@17/umd/react.production.min.js"></script>
<script src="https://unpkg./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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744598630a4583044.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信