Search code examples
vue.jsvuejs2v-for

Access next index object's value within a loop - Vue JS


I wanted to check for a condition if a particular property of an object is same as the very next object's property in an array-of-objects, iterated through a v-for loop.

Sample JSON object:

[
  { Date: '21-July-2017', ...},
  { Date: '21-July-2017', ...},
  { Date: '25-July-2017', ...},
  ...
]

The requirement is to check if each consecutive Date value is same, so that we will hide the Date header in the UI.

<div v-for="(everyDay, dayIndex) in eachPost.values" v-bind:key="dayIndex">
  <div v-if="everyDay['Date'] !== eachPost.values[dayIndex+1].Date">
     THIS DOESN'T WORK
  </div>
</div>

Is there an alternative to accomplish this req?


Solution

  • Your problem is when you get to your last item in the array your dayIndex+1 object does not exist. It is undefined. What you need to do is in your template determine if your object is defined and go from there.

      <div v-for="(everyDay, dayIndex) in eachPost.values" v-bind:key="dayIndex">
       <template v-if="eachPost.values[dayIndex+1]">
          <div v-if="everyDay['Date'] !== eachPost.values[dayIndex+1].Date">
             THIS WORKS
          </div>
      </template>
    
     </div>
    

    Here is a jsFiddle of my working example