0

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

3
  • 3
    because you have allAvailableTimes[index-1] and for the first iteration the index would be 0 and allAvailableTimes[-1] is undefined for the first iteration itself thus it is returning error. Commented Apr 15, 2020 at 10:09
  • on the first iteration [index-1] is undefined. so before accessing your property, you need to check if allAvailableTimes[index-1] is defined Commented Apr 15, 2020 at 10:10
  • @japrescott I thought of doing if (index > 0) but then I'd be making this comparison at every iteration. any ideas on how to solve this in a smarter way? Commented Apr 15, 2020 at 10:13

2 Answers 2

1

For the first iteration, index will be 0, so index - 1 will be -1, which is undefined.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to add an extra check of index >= 1.

const displayAvailableTimes = availableTimesJSON.map( (item, index) =>
       index >= 1 && item.time === allAvailableTimes[index-1].time ? <span>2</span> : <div>show item</div>

4 Comments

Does this check then happens at every iteration? Could it be avoided?
Yes, it will check on each iteration. Do you want to avoid this check on each iteration?
It doesn't affect the outcome if it's still there, but I wondered if it could be avoided for the sake of performance.
I don't think that it will affect performance much. However, any attempt to avoid index >= 1 condition will create more conditions. One good way is to availableTimesJSON.slice(1).map(...).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.