gpt4 book ai didi

javascript - react : Filter multidimensional array object by value in component

转载 作者:行者123 更新时间:2023-12-03 03:04:35 24 4
gpt4 key购买 nike

我有一个像这样的对象数组:

var matchs = [
{
id: 10689,
sport: 'Tennis',
players: [
{
id: 22,
name:'Rafa Nadal',
country: 'Spain',
odds: {
bookie_1: 1.60,
bookie_2: 1.61,
bookie_3: 1.62
}
},
{
id: 23,
name:'Roger Federer',
country: 'Spain',
odds: {
bookie_1: 2.30,
bookie_2: 2.31,
bookie_3: 2.32
}
}
]
},
{
id: 12389,
sport: 'Tennis',
players: [
{
id: 45,
name:'Fernando Verdasco',
country: 'Spain',
odds: {
bookie_1: 3.20,
bookie_2: 3.21,
bookie_3: 3.22
}
},
{
id: 65,
name:'Andy Murray',
country: 'Spain',
odds: {
bookie_1: 1.20,
bookie_2: 1.21,
bookie_3: 1.22
}
}
]
}
];

我有一个 React 组件,它显示 map 内与 map 的所有匹配项。我尝试过做这样的事情但没有好的结果。

let country = 'spain';

const List = ({ matchs }) => {

return (
<div>
{matchs.map((match) =>

let my_filter = match.players.filter(player => player.country === country);
{my_filter ? (

<div className="match" key={match.id}>

<div className="id">{match.id}</div>

<div className="players">

{match.players.map((player, num) =>
<div className="player" key={num}>
<span className="player-country">{player.country}></span>
<span className="name">{player.name}</span>
</div>
)}

</div>

) : ()}
)}
</div>
);

}

执行此操作的正确方法是什么?

最佳答案

也许filter首先匹配(按玩家所在的国家/地区),然后map通过结果:

<div>
{matchs
.filter(match => match.players.find(player => player.country === country))
.map(match =>
<div className="match" key={match.id}>
...
</div>
)}
</div>

关于javascript - react : Filter multidimensional array object by value in component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47224157/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com