我在将API返回1000个对象后使用Fetch,我只想呈现前4个或具有最高值的值
我在结果上使用.map,但我不知道如何设置条件或限制.map结果?
{NowMovies.map(Movie=>(
<Col sm="3">
<Card key={Movie.id}className='Now_Playing' body>
<CardImg top width="100%" src={`https://image.tmdb.org/t/p/w200${Movie.poster_path}`}
alt=""/>
<CardTitle className='title' >{Movie.title}</CardTitle>
<CardText className='Text'>Rating:{Movie.vote_average}</CardText>
<Link to={'/movie/' + Movie.id } > <Button color="danger">Visit</Button>{' '}
</Link>
</Card>
</Col>```
答案 0 :(得分:0)
我不确定您对or the values with the highest value
的含义,但是如果您只想从数组中获取4个元素,则可以使用slice
。如果您将0作为第一个参数传递而将要获得的项数作为第二个参数传递,则slice
可以作为“限制”。
例如
let arr = [1,2,3,4,5]
arr.slice(0, 4) // [1,2,3,4]
// if you want to get your items starting from specific position:
arr.slice(1, 5) // [2,3,4,5]
{NowMovies.slice(0,4).map(Movie=>(
<Col sm="3">
<Card key={Movie.id}className='Now_Playing' body>
<CardImg top width="100%" src={`https://image.tmdb.org/t/p/w200${Movie.poster_path}`}
alt=""/>
<CardTitle className='title' >{Movie.title}</CardTitle>
<CardText className='Text'>Rating:{Movie.vote_average}</CardText>
<Link to={'/movie/' + Movie.id } > <Button color="danger">Visit</Button>{' '}
</Link>
</Card>
</Col>)}
答案 1 :(得分:0)
const NowMovies = [];
const MAX_RATING = 10;
// This is just a sample JSON array with random ratings between 1-10 in this example
for (let i = 0; i < 20; i++) {
NowMovies.push({ index: i, rating: Math.floor(Math.random() * MAX_RATING + 1) });
}
// This is how you sort your array in descending order by rating, and then return the first N results. 5 in this case.
const sortedArray = NowMovies.sort((a, b) => b.rating - a.rating).slice(0, 5);
console.log(sortedArray);
您需要编写一个自定义的排序方法来定义如何对数组进行排序,例如^
然后您可以切片以返回前N个结果。
修改数组后,可以使用.map呈现JSX。