supersize
supersize

Reputation: 14773

Access index in v-for when iterating over object

I am trying to access the index of an iteration in Vue's v-for binding.

This is the object:

const obj = {  
  obj1: {  
    some: 'data'
  },
  obj2: {  
    some: 'data'
  },
  obj3: {  
    some: 'data'
  }
}

and I'm looping over it:

<li v-for="(object, index) in obj" :key="index">{{ object.some }}</li>

The problem is that contrary to looping over an array the index variable in case of looping over an object like this does not hold the iteration index (e.g. 0, 1, 2) but actually holds the object name obj1, obj2, obj3.

Why is it behaving like that and how can I get my precious iteration index back in this case?

Upvotes: 3

Views: 1654

Answers (1)

Lassi Uosukainen
Lassi Uosukainen

Reputation: 1688

According to the documentation when iterating over an object the second parameter is the object key. To access the index you should add a third parameter as in the following example:

<div v-for="(value, name, index) in object">
  {{ index }}. {{ name }}: {{ value }}
</div>

Upvotes: 9

Related Questions