ReactJS map through Object

前端 未结 8 2117
别跟我提以往
别跟我提以往 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:09

      I am not sure why Aleksey Potapov marked the answer for deletion but it did solve my problem. Using Object.keys(subjects).map gave me an array of strings containing the name of each object, while Object.entries(subjects).map gave me an array with all data inside witch it's what I wanted being able to do this:

      const dataInfected = Object.entries(dataDay).map((day, i) => {
          console.log(day[1].confirmed);
      });
      

      I hope it helps the owner of the post or someone else passing by.

      0 讨论(0)
    • 2021-01-31 17:11

      You get this error because your variable subjects is an Object not Array, you can use map() only for Array.

      In case of mapping object you can do this:

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

      Do you get an error when you try to map through the object keys, or does it throw something else.

      Also note when you want to map through the keys you make sure to refer to the object keys correctly. Just like this:

      { Object.keys(subjects).map((item, i) => (
         <li className="travelcompany-input" key={i}>
           <span className="input-label">key: {i} Name: {subjects[item]}</span>
          </li>
      ))}
      

      You need to use {subjects[item]} instead of {subjects[i]} because it refers to the keys of the object. If you look for subjects[i] you will get undefined.

      0 讨论(0)
    • 2021-01-31 17:16

      I use the below Object.entries to easily output the key and the value:

      {Object.entries(someObject).map(([key, val], i) => (
          <p key={i}>
              {key}: {val}
          </p>
      ))}
      
      0 讨论(0)
    • 2021-01-31 17:19

      Map over the keys of the object using Object.keys():

      {Object.keys(yourObject).map(function(key) {
        return <div>Key: {key}, Value: {yourObject[key]}</div>;
      })}
      
      0 讨论(0)
    • 2021-01-31 17:30

      Use Object.entries() function.

      Object.entries(object) return:

      [
          [key, value],
          [key, value],
          ...
      ]
      

      see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

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