简体   繁体   中英

map first object from api in javascript

I map my arrays via

moviesList.map(movie => <MovieCard movieID={movie} key={movie} 

but my API gives sometimes 1 or more results. How can I change my .map to show only the first result?

First of all, writing moviesList[0].map will make your loop crash if [0] is an object, because it won't be iterable. So you basically need to get rid of all objects but the first one. You can do it with slice(). Here, slice(0,1) means "take all element from 0 to 1 in the array". So only the first object will survive. Then your map() will work like a charm. Also, the key is a basic number "i", obtained from map(), which is better than passing a whole object. If you want to use an object property for a key, please use something like movie.id, and not movies as a whole.

 moviesList.slice(0,1).map((movie,i)=> <<MovieCard movieID={movie} key={i}/>)

试试这个

[moviesList[0]].map(movie => <MovieCard movieID={movie} key={movie} 

Try this,

moviesList[0].map(movie=><MovieCard movieID={movie} key={movie}/> )

Or if you only want to show only one. Try this,

<MovieCard movieID={moviesList[0]} key={moviesList[0]}/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM