Categories
Vue Answers

How to Check for the Last Property of an Object in a v-for Loop?

Spread the love

Sometimes, we want to check for the last property of an object in a v-for loop.

In this article, we’ll look at how to check for the last property of an object in a v-for loop.

Check for the Last Property of an Object in a v-for Loop

We can check for the last property of an object in a v-for loop with the index property with the index loop variable.

For instance, we can write:

<template>  
  <div id="app">  
    <p 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>  
    </p>  
  </div>  
</template>  
<script>  
export default {  
  name: "App",  
  data() {  
    return {  
      person: { name: "Joe", age: 35, department: "IT" },  
    };  
  },  
};  
</script>

We get the property value with val .

And we get the property name with key .

The index has the index of the property being looped through.

We get the number of properties in person with Object.keys(person).length .

So we subtract that by 1 to get the index of the last property in person .

Conclusion

We can check for the last property of an object in a v-for loop with the index property with the index loop variable.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *