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.
In Plain English
Thank you for being a part of our community! Before you go:
- Be sure to clap and follow the writer! 👏
- You can find even more content at PlainEnglish.io 🚀
- Sign up for our free weekly newsletter. 🗞️
- Follow us on Twitter(X), LinkedIn, YouTube, and Discord.