alexschomb
alexschomb

Reputation: 126

Vue.js access nested object in v-for loop

I'd like to access the "newest" object of a nested object array inside another object array in Vue.js. Please see the example below.

Example Object elements:

[
  {
    'name': 'foo',
    'content': [
      {
        title: 'bar'
      }
    ]
  },
  {
    'name': 'hello world',
    'content': [
      {
        'title': 'this is a test'
      },
      {
        'title': 'this another test'
      }
    ]
  }
]

Simplified vue code:

<div v-for="{ element, index } in elements" :key="index">
  <h1>{{ element.name }}</h1>
  <p>Latest content: {{ element.content[element.content.length - 1].title }}</p>
</div>

Why is that not working? Vue says that element.content is undefined.

Upvotes: 1

Views: 3095

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

Remove {} from v-for="{ element, index } in elements" and replace them by ()

Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#app',

  data() {
    return {
      elements: [{
          'name': 'foo',
          'content': [{
            title: 'bar'
          }]
        },
        {
          'name': 'hello world',
          'content': [{
              'title': 'this is a test'
            },
            {
              'title': 'this another test'
            }
          ]
        }
      ]
    }
  }
});
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>


<div id="app" class="container">
  <div v-for="( element, index ) in elements" :key="index">
    <h1>{{ element.name }}</h1>
    <p>Latest content: {{ element.content[element.content.length - 1].title }}</p>
  </div>
</div>

Upvotes: 1

Related Questions