通过嵌套数组循环,并且能够搜索/过滤它



今天我来这里是想就我遇到的一个问题寻求一些帮助。

所以我正在制作一个仪表板,在那里它可以循环通过刑事指控。

所以我把它设置在一个数据库中,表的结构看起来像这个

category charges

因此,它包含了类别,以及属于该类别的特定电荷。

所以我想做的是,循环通过类别,在类别内部循环也循环通过该类别的费用。

我知道我可以通过映射每个类别来做到这一点,然后在第一个映射中映射电荷。但后来我们遇到了一个问题。问题是我该如何过滤?例如,我想通过";标题";键入每个类别的费用,所以如果我搜索,它将过滤掉,只显示任何类别中匹配的费用。

这是我的数据结构:(这就是电荷数据状态中的内容(

0: {category: "Infractions", charges: Array(30), color: "#417011", id: 1}
1: {category: "Misdemeanors", charges: Array(60), color: "#7e5800", id: 2}
2: {category: "Felonies", charges: Array(99), color: "#7e2100", id: 3}

收费结构:

0: {fine: "500", months: "0", points: "0", title: "Failure to stop at Red Light"}
1: {fine: "500", months: "0", points: "0", title: "Failure to stop at Stop Sign"}

我目前的代码,正如我在帖子中解释的那样:

<div className="outer-content">
{chargesData && chargesData.length > 0 ? (
chargesData.map((cat) => (
<div className="inner-content">
<Typography style={{ color: '#fff', wordBreak: 'break-word' }} variant="h6" gutterBottom>{cat.category}</Typography>
<div className="inner-content-body" style={{ flexDirection: 'row', flexWrap: 'wrap', flex: '0', overflowY: 'unset', paddingLeft: '1.5%' }}>
{cat.charges && cat.charges.length > 0 ? (
cat.charges.map((charge) => (
<Typography style={{ color: '#fff', wordBreak: 'break-word', textAlign: 'center' }} variant="body1" gutterBottom>{charge.title}</Typography>
<Typography style={{ color: '#fff', wordBreak: 'break-word', textAlign: 'center' }} variant="body2" gutterBottom>{charge.months !== undefined ? charge.months : '0'} months</Typography>
<Typography style={{ color: '#fff', wordBreak: 'break-word', textAlign: 'center' }} variant="body2" gutterBottom>{charge.fine !== undefined ? charge.fine : '$0.0'}</Typography>
<Typography style={{ color: '#fff', wordBreak: 'break-word', textAlign: 'center' }} variant="body2" gutterBottom>{charge.points !== undefined ? charge.points : '0'} point(s)</Typography>
))
) : (
<></>
)}
</div>
</div>
))
) : (
<></>
)}
</div>

希望有人能找到答案,再次感谢您的阅读。

致以亲切的问候。

保持过滤字符串处于状态

const [chargeTitleSearch, setChargeTitleSearch] = useState("");

然后你可以创建过滤功能

const filterFn = t => !chargeTitleSearch || t.match(chargeTitleSearch); // or whatever

然后使用过滤器

cat.charges.filter(c => filterFn(c.title)).map(...);

如果您想省略筛选后没有数据的任何类别:

// Make a new list with the charges in each category filtered out
const filterChargeData = chargesData.map(c => {
return { ...c, charges: c.charges.filter(cc => filterFn(cc.title))};
});
// Filter the categories based on whether or not they contain any charges.
const nonEmptyCategories = filterChargeData.filter(c => c.charges.length);

最新更新