简体   繁体   English

动态显示对象数组

[英]Dynamically display array of objects

Using React, I am trying to dynamically display my array of objects into a side navigation.使用 React,我试图将我的对象数组动态显示到侧边导航中。 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.如果您首先需要将数组转换为这种数据结构,您将需要利用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
}, [])

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>)}
  </>
))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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