How to check if you are on the last property of an object in a v-for loop with Vue.js?

Sometimes, we want to check if you are on the last property of an object in a v-for loop with Vue.js.

In this article, we’ll look at how to check if you are on the last property of an object in a v-for loop with Vue.js.

How to check if you are on the last property of an object in a v-for loop with Vue.js?

To check if you are on the last property of an object in a v-for loop with Vue.js, we can use the index and the Object.keys method.

For instance we write

<template>
  <div>
    <span v-for="(val, key, index) of person" :key="key">
      key: {{ key }}, val: {{ val }}, index: {{ index }}
      <span v-if="index !== Object.keys(person).length - 1">, </span>
    </span>
  </div>
</template>

to get the index of the property being looped through in the person object.

And we check if we aren’t on the last property of person with

index !== Object.keys(person).length - 1

We use to Object.keys return an array of property keys in the person object and we get the length of that to get the number of properties in the object.

Conclusion

To check if you are on the last property of an object in a v-for loop with Vue.js, we can use the index and the Object.keys method.