简体   繁体   中英

Dynamically display array of objects

Using React, I am trying to dynamically display my array of objects into a side navigation. Is there an effecient way to map and display my values cleanly? I've tried dividing tabs and title into two seperate arrays and removing the duplicates from tab. Then I was able to map and display the tabs but how would I do this for the titles? Is there an easier solution

Something like this but not hard coded in.

<div>Lead</div>
   <div>new lead</div>
   <div>reached out</div>
<div>Applicant</div>
   <div>new applicant</div>
   <div>recruiter screen</div>
<div>Interview</div>
   <div>exploratory chat</div>
   <div>hired</div>

My array of objects:

nav = [
    {tab: "Lead", title: "new lead"},
    {tab: "Lead", title: "reached out"},
    {tab: "Applicant", title: "new applicant"},
    {tab: "Applicant", title: "recruiter screen"},
    {tab: "Interview", title: "exploratory chat"},
    {tab: "Interview", title: "hired"},
]

Are you asking about how to structure your data? If so, you could create an array of objects to group them together like so:

const nav = [
  { tab: "Lead", titles: [ "new lead", "reached out" ] },
  { tab: "Applicant", titles: [ "new applicant", "recruiter screen" ] },
  { tab: "Interview", titles: [ "exploratory chat", "hired" ] },
]

If you first need to convert the array to this data structure you would want to leverage the Array.reduce higher-order method.

nav.reduce((accumulator, navItem) => {
  const exists = accumulator.find((existingNav) => existingNav.tab === navItem.tab)

  if (exists !== undefined) {
    exists.titles.push(navItem.title)
  } else {
    accumulator.push({ tab: navItem.tab, titles: [ navItem.title ] })
  }

  return accumulator
}, [])

To render this to the desired output, you could do this:

nav.map((navItem) => (
  <>
    <div>{navItem.tab}</div>
    {navItem.titles.map((title) => <div>{title}</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