我有一个像这样的对象数组:
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>
);
}
这样做的正确方法是什么?
答案 0 :(得分:1)
可能filter
首先匹配(按播放器的国家/地区),然后map
匹配结果:
<div>
{matchs
.filter(match => match.players.find(player => player.country === country))
.map(match =>
<div className="match" key={match.id}>
...
</div>
)}
</div>