Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get key, value, and index in v-for

Tags:

vue.js

v-for

I am using v-for to loop through an object, I need to access the key, the value, and the index. I've seen many ways to access two of them, that's easy, but can't find how to access all three.

I found a workaround but it's horribly messy and pretty unreadable.

<div v-for="idx in Object.keys(PointsAvailable[0]).length" :key="idx">
  <PointSquare
    :Value="Object.keys(PointsAvailable[0])[idx-1]"
    :Availability="PointsAvailable[0][Object.keys(PointsAvailable[0])[idx-1]]"
    :reference="idx-1">
  </PointSquare>
</div>

Is there a better way of doing this?

like image 837
aidan byrne Avatar asked Sep 02 '25 05:09

aidan byrne


1 Answers

You can also try v-for="(value, key, index) in PointsAvailable" and reference them accordingly. Check this example from the Vue documentation:

<div v-for="(value, name, index) in object">

{{ index }}. {{ name }}: {{ value }}

https://v2.vuejs.org/v2/guide/list.html

like image 159
Fahd Arafat Avatar answered Sep 05 '25 00:09

Fahd Arafat