1

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.

0

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your fast and correct answer! it did solve only parts of my error, but helped me debug and solve the rest. (FYI: the overall app the main error was that I pushed the object array the wrong way. again getting rid of the curly braces solved the issue!)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.