Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading