Home > Mobile >  How to access JSON type object property stored inside data object in Vue's template?
How to access JSON type object property stored inside data object in Vue's template?

Time:09-28

I have a data object in a Vue.js app

data() {
  return {
    group1: {
      id:   'qd4TTgajyDexFAZ5RKFP',
      owners: {
        john:  {age: 32, gender: 'man'},
        mary: {age: 34, gender: 'woman'},
      }
    }
  }
}

I'm trying to get Mary's age inside Vue's template like this...

I can get to owners like this...

<p>{{group1.owners}}</p>

but if I try to drill further like this...

<p>{{group1.owners.mary.age}}</p>

...I get an error message saying it can't get to mary of undefined .

"TypeError: Cannot read properties of undefined (reading 'id')"

Anyone out there who can help?

CodePudding user response:

Try that rather

<script>
  export default {
    data() {
      return {
        group1: {
          id: 'qd4TTgajyDexFAZ5RKFP',
          owners: {
            john: {
              age: 32,
              gender: 'man'
            },
            mary: {
              age: 34,
              gender: 'woman'
            },
          }
        }
      }
    }
  }
</script>

<template>
  <pre>result: {{ group1.owners.mary.age }}</pre>
</template>

Here is a working example.

  • Related