admin管理员组文章数量:1134555
I would like to ask how can I limit my .map
loop for example to a 5 items only because currently when I access an api it returns 20 items. but I want to display only 5. Mostly that I found is just looping all throughout the array of objects and not limiting it to a number of items.
Note: I have no control on the API because I'm just using the moviedb api
Here's my code:
var film = this.props.data.map((item) => {
return <FilmItem key={item.id} film={item} />
});
return film;
I would like to ask how can I limit my .map
loop for example to a 5 items only because currently when I access an api it returns 20 items. but I want to display only 5. Mostly that I found is just looping all throughout the array of objects and not limiting it to a number of items.
Note: I have no control on the API because I'm just using the moviedb api
Here's my code:
var film = this.props.data.map((item) => {
return <FilmItem key={item.id} film={item} />
});
return film;
Share
Improve this question
edited Mar 14, 2019 at 0:10
brooksrelyt
4,0256 gold badges35 silver badges57 bronze badges
asked Feb 21, 2017 at 18:12
Sydney LoteriaSydney Loteria
10.4k21 gold badges62 silver badges73 bronze badges
0
5 Answers
Reset to default 322You could use Array#slice
and take only the elements you need.
var film = this.props.data.slice(0, 5).map((item) => {
return <FilmItem key={item.id} film={item} />
});
return film;
If you do not need the original array anymore, you could mutate the array by setting the length to 5
and iterate them.
You could use filter() as well
var film = this.props.data.filter((item, idx) => idx < 5).map(item => {
return <FilmItem key={item.id} film={item} />
});
return film;
You can also limit it by passing a second argument to a map()
callback, which would be an index of an item in the loop.
const film = this.props.data?.map(
(item, index) =>
index < 5 && ( // <= only 5 items
<FilmItem
key={item.id}
film={item}
/>
)
);
return film;
However, you probably should stick to Nina's answer unless you really need some elegancy in your code. Since I'm guessing my answer would be slower performance-wise.
References:
- MDN: map() syntax
- Optional Chaining
Hi, If you are using a functional component. you can try this:
<p>const [film, setFilm] = useState([])</p>
<i>// Fetch data from API</i>
<p>useEffect(() =>{...})</p>
var fiveFilm = film.slice(0,5)
in your return function:
you can map using:
{fiveFilm.map(item => <p>{item.name}<p>)}
here is the way you can limit items using map function.
const result = array.map((value, index) => {
// * need only 10 items
if (index >= 10) {
return;
}
return <div key={index}>Text</div>;
});
本文标签: javascriptLimit items in a map loopStack Overflow
版权声明:本文标题:javascript - Limit items in a .map loop - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736800453a1953468.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论