sandesh phuyal
sandesh phuyal

Reputation: 73

Vue cannot read property of null while using v-for

Is there a way to solve an error which says id not defined on v-bind:key="persons.id" ?

My View

<div v-for="reservation in reservationNameByTime" v-bind:key="reservation.id">
  {{reservation.id}} /** displays 1 **/
  <div v-for="player in reservation.Players" v-bind:key="player.id">
    {{player.id}} /**displays 1 **/
    <div v-for="persons in player.Person" v-bind:key="persons.id"> /** throws an error as id of null **/
      {{persons.name}}
    </div>
  </div>
</div>

JSON DATA

reservationNameByTime: [
 {
  id: 1,  /** defines reservation id **/
  Players: [
    id: 1,  /** defines players id **/
    Person:{
      id: 1,  /** defines the person id **/
      name: John
    }
   ]
 }
]

Image for array data

JSON array data

Upvotes: 1

Views: 1013

Answers (3)

D Malan
D Malan

Reputation: 11414

player.Person is an object and v-for on an object iterates through the properties of the object and returns its values. In this case it would be 1 and John. So you're trying to get 1.id and John.id.

If you're only going to have one person, you could just do:

div v-bind:key="player.Person.id">
   {{player.Person.name}}
</div>

Upvotes: 0

Adrien Leloir
Adrien Leloir

Reputation: 503

Your data is malformed, try this with the html code in your post

reservationNameByTime: [{
    id: 1,
    Players: [{
        id: 1,
        Person: [{
            id: 1,
            name: 'John'
        },
        {
            id: 2,
            name: 'Marc'
        }]
    }]
}]

But this (below) is better, for each reservation, you have an id and a list of players, player have id and name

reservation: [{
    id: 1,
    players: [{
        id: 21,
        name: 'John'
    },
    {
        id: 55,
        name: 'Marc'
    }]
},
{
    id: 2,
    players: [{
        id: 34,
        name: 'Adrien'
    },
    {
        id: 12,
        name: 'Marion'
    }]
}]

HTML / VUE

<div v-for="reservation in reservations" v-bind:key="reservation.id">
    {{reservation.id}}
    <div v-for="player in reservation.players" v-bind:key="player.id">
        {{player}}
    </div>
</div>

Upvotes: 0

Willing Master
Willing Master

Reputation: 91

<div v-for="(reservation, i) in reservationNameByTime" v-bind:key="i">
    {{reservation.id}} /** displays 1 **/
    <div v-for="(player, j) in reservation.Players" v-bind:key="j">
        {{player.id}} /**displays 1 **/
        <div v-for="(persons, k) in player.Person" v-bind:key="k">
            {{persons.name}}
        </div>
    </div>
</div>

Upvotes: 1

Related Questions