I have a small similar array of
const arr = [{ "0": "First Item", "1": "Second Item", "2": "Third Item"}]
And I want to output that in JSX.
This is what I have https://codesandbox.io/s/focused-bose-wgmbny?file=/src/App.js. As you can see, it only outputs the first element of the array.
I have tried using forEach and for loops to no avail. (And developers tell me you should use .map for JSX)
I also tried this:
arr.map((item, index) => (
<p>{item[index]}</p>
))
I just want the map to output:
"First Item"
"Second Item"
"Third Item"
but it just stops at "First Item"
3
Answers
It’s an array with a single object as its element.
When you use map function on
arr
like this:It iterates over the elements in
arr
, and for each element (which is the single object in this case) it returns property with keyindex
(which is index of currentmap
iteration). So actually you are invokingarr[0][0]
here.Correct array would be:
Then you can print each item:
@steve You have to consider multiple points here
To fix this
Approach 1
Approach 2
in your example array only have 1 object
and you loop through it
and map will loop only once. it will return your object;
your item is { "0": "First Item", "1": "Second Item", "2": "Third Item"};
and index always 0 because it will loop only once.
and you use item[index]
which means your item is object above
and item[index] means only key of object