1

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?

1
  • Better way would be to use a computed property and filter them as unique, would keep your view cleaner. Commented Jul 2, 2018 at 20:52

1 Answer 1

4

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

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

Comments

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.