简体   繁体   中英

How to loop through nested objects in reactjs?

Since this in an object i doing this but it doesn't work. How would I get the 'key' field through a loop?

  <div>
      <ul>
        {tickets && tickets.issues && Object.keys(tickets.issues).map((issue, i) =>
        (
          <li key={i}>
            Issue number: {tickets.issues.key}
          </li>
         ))}
      </ul>
  </div>

SOLUTION

   <div>
      <ul>
       {this.state.tickets && this.state.tickets.issues && Object.keys(this.state.tickets.issues).map((issue, i) =>
       (
        <li key={i}>
           Issue number: {this.state.tickets.issues[i].key}
        </li>
      ))}
      </ul>
  </div>

在此处输入图片说明

Looking at your response image the key field exists in issues[] but not in fields, so it should be fine just (no nesting required):

{ Object.keys(tickets.issues).map((issue, i) => (
  <li key={issue.key}>
   Issue number: {issue.key}
  </li>
))}

If you have the key in fields (not expanded in the image)

{ Object.keys(tickets.issues).map((issue, i) => (
  Object.keys(issue.fields).map(field=>(
 <li key={field.key}>
   Issue number: { field.key }
 </li>
)
))}

tickets.issues is an Array of Objects, so:

const { issues } = tickets;
issues.map(issue => console.log(issue.key));

A simple solution

  <div>
    <ul>
      {tickets && tickets.issues && Object.keys(tickets.issues).map((issue, i) => 
     (
      <li key={i}>
         Issue number: {tickets.issues.key}
      </li>
    ))}
    </ul>
  </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM