简体   繁体   中英

how to iterate through objects, react

I want to make the following code iterate through an object I created.

function itemContent(number) {
  return (
    <div >
      <div className="item">
          <div className="itemPic">
            <img src={work.worked[i].picture} alt={work.worked[i].alt} />
          </div>
          <div className="itemInfo">
            <div className="itemInfoLeft">
              <p>{work.worked[i].title}</p>
              <p>{work.worked[i].intro}</p>
            </div>
            <div className="itemInfoRight">
              <p>{work.worked[i].source}</p>
              <p>{work.worked[i].date}</p>
            </div>
          </div>
        </div>
      </div>
  )
}

The following is my object:

const worked = {
  redo: {
    picture: `../../images/redo_logo.jpg`,
    alt: `----`,
    title: `/////`,
    source: `RE-DO consulting`,
    intro: `lorem`,
    date: `Aug 2020 -`,
  },
  kth: {
    picture: `../../images/kth_Building.jpg`,
    alt: `-------`,
    title: `hmm`,
    source: `bleh`,
    intro: `lorem.`,
    date: `Aug 2020 -`,
  },

As you can see I only want the code to iterate through the first objects (redo and kth). Any idea how to do this?

Any help is appreciated.

Do you mean something like this?

function itemContent(number) {
  const workedItems = Object.values(work.worked);
  return (
    <div>
    {workedItems.map(item =>
      <div className="item">
          <div className="itemPic">
            <img src={item.picture} alt={item.alt} />
          </div>
          <div className="itemInfo">
            <div className="itemInfoLeft">
              <p>{item.title}</p>
              <p>{item.intro}</p>
            </div>
            <div className="itemInfoRight">
              <p>{item.source}</p>
              <p>{item.date}</p>
            </div>
          </div>
        </div>
      }
      </div>
  )
}

Object.values(work.worked) returns following array:

[
  {
    "picture": "../../images/redo_logo.jpg",
    "alt": "----",
    "title": "/////",
    "source": "RE-DO consulting",
    "intro": "lorem",
    "date": "Aug 2020 -"
  },
  {
    "picture": "../../images/kth_Building.jpg",
    "alt": "-------",
    "title": "hmm",
    "source": "bleh",
    "intro": "lorem.",
    "date": "Aug 2020 -"
  }
]

If you only want to iterate over redo and kth and ignore other keys of work.worked you can use this:

const workedItems = [work.worked.redo, work.worked.kth];

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