I have two json inside a react app and I want to filter the ids.
{data.investments.map((item) => (
<div className="tipo">
<h1 key={item.id}>{item.description}</h1>
<h2>
Rendimento total: <span>valor</span>
</h2>
{/* SECOND LOOP */}
{data.reports.map((rep) => (
<div>
<Tabela reports={data.reports} tipoInvestimento={item.id} />
</div>
))}
</div>
))}
On the element inside the second loop, I need to show only the elements that match the Id with the first loop
import React from "react";
export const Tabela = ({ reports }, { tipoInvestimento }) => {
return (
<table>
{reports.map((r) => {
if (r.id === tipoInvestimento)
return (
<tr key={r.id}>
<div>
<td>
{r.month}/{r.year}
</td>
<td>R$ {r.value.toFixed(2)}</td>
</div>
<td>{tipoInvestimento}</td>
</tr>
)}}
</table>
);
};
but nothing shows. Is there any other form to do it? Thanks in advance.
CodePudding user response:
You can use Array.filter() function to only iterate over some of the items based on a condition:
{data.investments.map((item) => (
<div className="tipo">
<h1 key={item.id}>{item.description}</h1>
<h2>
Rendimento total: <span>valor</span>
</h2>
{/* SECOND LOOP */}
{data.reports.filter(r => r.id === item.id).map((rep) => (
<div>
<Tabela reports={data.reports} tipoInvestimento={item.id} />
</div>
))}
</div>
))}