动态显示对象数组



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

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

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

最新更新