【问题标题】:Dynamically display array of objects动态显示对象数组
【发布时间】:2021-01-30 08:26:42
【问题描述】:

使用 React,我试图将我的对象数组动态显示到侧面导航中。有没有一种有效的方法来清晰地映射和显示我的价值观?我尝试将选项卡和标题分成两个单独的数组并从选项卡中删除重复项。然后我能够映射和显示选项卡,但我将如何为标题执行此操作?有没有更简单的解决方案

类似的东西,但没有硬编码。

<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>

我的对象数组:

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"},
]

【问题讨论】:

    标签: javascript html arrays reactjs jsx


    【解决方案1】:

    您是否在询问如何构建数据?如果是这样,您可以创建一个对象数组来将它们组合在一起,如下所示:

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

    如果您首先需要将数组转换为这种数据结构,您可能需要利用Array.reduce 高阶方法。

    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
    }, [])
    

    要将其呈现为所需的输出,您可以这样做:

    nav.map((navItem) => (
      <>
        <div>{navItem.tab}</div>
        {navItem.titles.map((title) => <div>{title}</div>)}
      </>
    ))
    

    【讨论】:

    • 我在问如何在 div 中显示它们以看起来像我给出的示例。以这种方式将它们构建在一组对象中可能会有所帮助。
    • @MichaelLee 我更新了我的答案,如果能回答你的问题,请告诉我。
    • 如何将我现在拥有的数据转换为您提供的对象数组?
    • 我将再次更新答案,向您展示如何将当前数据结构转换为我建议的数据结构。
    猜你喜欢
    • 2013-09-13
    • 2015-06-02
    • 2021-04-06
    • 2019-03-14
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-06
    相关资源
    最近更新 更多