how to get key, value, and index in v-for
Asked Answered
B

4

27

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?

Bodgie answered 10/1, 2021 at 15:37 Comment(0)
R
68

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

Rondon answered 10/1, 2021 at 16:39 Comment(0)
R
9

You can use Object.entries(obj) to get the key and value of the object and to get the index you can define the for loop as:

<div v-for="(value, index) in Object.entries(points)" :key="index">
    {{ value[0] }} {{ value[1] }} {{ index }}
</div>

value[0] is the key, value[1] is the value and index

Rus answered 10/1, 2021 at 16:10 Comment(2)
You would expect to be able to use v-for=(key, value) in Object.entries(points) but this doesn't work as expected. The first item in the pair is actually a list, like the answer post says.Paraldehyde
v-for="(value, name, index) in object" (which I was expecting to work) was just giving me the index number rather than the string value of the keys. v-for="(value, index) in Object.entries(points)" followed by {{ value[0] }} {{ value[1] }} worked as expected, where I get [KEY_STRING_VALUE]: [KEY_VALUE] 👍Stroboscope
N
1
v-for="([key, value]) in Object.entries(Obj)"

this should work (original)

Ness answered 12/6, 2023 at 13:17 Comment(0)
E
1
v-for="([key, value], index) in Object.entries(Obj)"

This should work.

Enlil answered 25/7, 2023 at 10:7 Comment(1)
Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community?Beer

© 2022 - 2024 — McMap. All rights reserved.