I have a JSON file as follows:
[
{
"id": "0",
"type": "time",
"day": "today",
"time": "0700"
},
{
"id": "1",
"type": "time",
"day": "today",
"time": "0700"
},
...
]
I can convert it to an array and access its properties:
const allAvailableTimes = availableTimesJSON.map(item => item)
console.log(allAvailableTimes[0].time) // 0700
If I try to access one of these properties using the index of a map function, that won't work:
const displayAvailableTimes = availableTimesJSON.map( (item, index) =>
item.time === allAvailableTimes[index-1].time ? //cannot read property 'time' of undefined
<span>2</span>
: <div>show item</div>
What I am trying to do is, if a time has already been rendered, display the number 2 to next to it:
07:00²
I am trying to do this by comparing the 'time' property of the current element with the 'time' property of the previous element.
I am mapping over the original JSON file availableTimesJSON, but even if I change it to the array allAvailableTimes (with the exact same content), it'll still return undefined
allAvailableTimes[index-1]and for the first iteration the index would be 0 andallAvailableTimes[-1]is undefined for the first iteration itself thus it is returning error.[index-1]is undefined. so before accessing your property, you need to check ifallAvailableTimes[index-1]is definedif (index > 0)but then I'd be making this comparison at every iteration. any ideas on how to solve this in a smarter way?