我正在开发一个React JS应用程序,这是一个比赛比分预测应用程序。
使用以下代码,应用程序当前显示即将到来的比赛列表,用户可以单击并输入预测。
if(!this.props.loading && !this.props.error){
upcomingmatches = this.props.upcmgMatches.map(upcomingMatch => {
return <UpcomingMatch
key={upcomingMatch.id}
teamA={upcomingMatch.teamA}
teamB={upcomingMatch.teamB}
matchKickoff={upcomingMatch.matchKickoff}
clicked={() => this.addInitInputMatchResultHandler(upcomingMatch.id, upcomingMatch.teamA, upcomingMatch.teamB, upcomingMatch.matchKickoff)}
/>
});
}
我想修改它,以便如果用户已经为匹配做出了预测,那么它将显示组件,但带有额外的信息,例如他们当前的预测。
我的组件可以访问两个对象数组,这两个对象数组是从Firebase表接收并转换为数组的。
upcmgMatches
显示用户可以预测的所有当前即将到来的匹配。
userPredictions
显示了用户预测的所有比赛,但仍然没有播放。所以这可以包括upcmgMatches
中的所有匹配,如果他们对所有匹配进行了预测,或者只是这些匹配的子集,或者如果他们没有进行任何预测,我猜是一个空数组。
这些数组如下所示。
因此,来自upcmgMatches
的id
应该与userPredictions
中的matchID
匹配
upcmgMatches = [{
"matchKickoff": "2018-09-22T10:45",
"teamA":"Roosters",
"teamB":"Dragons",
"id":"-LN-pNFv-rFJQkunM1Tv"
},
{
"matchKickoff": "2018-09-22T19:00",
"teamA": "Storm",
"teamB": "Sharks",
"id": "-LMrXWzcEjN_u_jlULuJ"
}]
userPredictions = [{
"matchID": "-LMrXWzcEjN_u_jlULuJ",
"teamAName": "Storm",
"teamAScore": "22",
"teamBName": "Sharks",
"teamBScore": "12",
"userId": "J2QO4OHT5vc7aAkT9vcdREo1IuW2",
"id": "-LMvzSoaMAhBUhgWMOpM"
}]
所以我想我修改后的逻辑应该是..
对于upcmgMatches
中的每个匹配项,在matchID
字段中检查id
是否存在于userPredictions
中,如果存在,则返回UpcomingMatch组件以及来自userPredictions的附加信息,即TeamAScore和teamBScore。如果不是,那么就从upcmgMatches
返回信息,这些信息应该是相同的,但没有预测分数。
发布于 2018-09-26 01:15:08
您可以使用Object.keys()获取外部对象键
const getFirstKey = o => Object.keys(o)[0]
const getMatchIds = matches => matches.map(getFirstKey)
然后,您可以对照它检查userPredictions的列表。
const isUserMatch = matchKey =>
getMatchIds(userPredictions)
.includes(matchKey)
const upcomingUserMatches = upcomingMatches
.map(getFirstKey)
.filter(isUserMatch)
https://stackoverflow.com/questions/52501633
复制相似问题