Home > Blockchain >  Slicing JSON data?
Slicing JSON data?

Time:10-09

I am trying to figure out a way to take the first 5 items out of an array of 80 and put them into an unordered list. I am mapping the data like this but not sure how to only collect the first 5 results. <ul>{data.moves.map((item) => (<li key={index}>{item.move.name} </li>))</ul> I also tried instead of passing the entire array through the map to slice the first 5 off but I could not get that to work for me.

Any thoughts? Thanks!

CodePudding user response:

Like any array in JS, you can just use

arr.slice(0, 5)

to take the first 5 elements. Note that .slice() returns a new array. Docs.

CodePudding user response:

This is a quick thing you can do:

<ul>{data.moves.map((item, idx) => (idx < 5) && (<li key={index}>{item.move.name} </li>))</ul>

That will show only the first 5 items.

  • Related