Problem `v-for` on Array of nested object (property "nested prop" of undefined)?


#1

I base on Meteor.
I get data from server with Array of nested object

data = [
  {id: , date, accountDoc: {name: ....., nestedDoc: { code: ........}}}
]
----
<template>
<ul>
  <li v-for="item in results" :key="item.id">
   Code: {{item.accountDoc.nestedDoc.code}}
  </li>
</ul>
</template>
export default {
  data(){
    return {results: []}
  },
  methods: {
    submitForm() {
          getData
            .callPromise(this.params)
            .then(result => {
              this.results = result
            })
            .catch(error => {
              ...
            })
    }
  }
}

Sometime get error property "code" of undefined.
But the results is work fine with full data.


#2

Put a console.log(result) inside the getData().then callback. Then, next time you get the error take a look at what the result is - you’ll probably find result (or one of the items in the array) is not in the format you are expecting.

For example, what does getData return if there are no results? or only one result? I’ve come across API’s which returned mutliple results in an array but if there is only one result it returns the object itself not in an array. Very unhelpful!

Edit: Actually since the error message is 'property "code" of undefined', that tells us that in one of your results accountDoc exsits but accountDoc.nestedDoc doesn’t exist. Otherwise the error would be 'property "nestedDoc" of undefined'. You either need to fix your source data or make your template more resilient to missing data.


#3

I console.log on

.then(result => {
  console.log(result) /// data is fine with full structure
  this.results = result
})

#4

And when the data is fine with full structure, do you still get the error 'property "code" of undefined'?

Is there anywhere else in your javascript or template where you referencing any property called "code"?

Try this:

.then(result => {
  console.log(result)
  result.forEach(r => {
      console.log(r);
      console.log(r.accountDoc.nestedDoc.code); // put this in a separate console.log so if it fails the one above will tell you WHICH one failed 
   });
  this.results = result
})

Also try this:

  <li v-for="item in results" :key="item.id">
   Code: {{item.accountDoc.nestedDoc ? item.accountDoc.nestedDoc.code : 'nestedDoc undefined in '+item.id}}
  </li>

If that all works OK but you still get the 'property "code" of undefined' but no other error messages in your console or rendered list, then you must be referencing “code” somewhere else.

If you still can’t find the cause of the bug then you need to isolate a “results” dataset which causes the error, then create a stripped down version of your code on codepen, trinket, etc which demonstrates the error with hard-coded “results” data.