ReactJS map through Object

前端 未结 8 2111
别跟我提以往
别跟我提以往 2021-01-31 16:53

I have a response like this:

I want to display the name of each object inside this HTML:

{subjects.map((item, i) => (
  
  • 相关标签:
    8条回答
    • 2021-01-31 17:33

      When calling Object.keys it returns a array of the object's keys.

      Object.keys({ test: '', test2: ''}) // ['test', 'test2']

      When you call Array#map the function you pass will give you 2 arguments;

      1. the item in the array,
      2. the index of the item.

      When you want to get the data, you need to use item (or in the example below keyName) instead of i

      {Object.keys(subjects).map((keyName, i) => (
          <li className="travelcompany-input" key={i}>
              <span className="input-label">key: {i} Name: {subjects[keyName]}</span>
          </li>
      ))}
      
      0 讨论(0)
    • 2021-01-31 17:33

      Also you can use Lodash to direct convert object to array:

      _.toArray({0:{a:4},1:{a:6},2:{a:5}})
      [{a:4},{a:6},{a:5}]
      

      In your case:

      _.toArray(subjects).map((subject, i) => (
          <li className="travelcompany-input" key={i}>
              <span className="input-label">Name: {subject[name]}</span>
          </li>
      ))}
      
      0 讨论(0)
    提交回复
    热议问题