1

I have a code as

<div v-for="benefit in service.benefits">
    <p>{{benefit}}</p>
</div>

and here is the data

service: [
  {title: 'blablabla',
  price: '123',
  benefits: ['a', 'b']},

  {title: 'blaaablabla',
  price: '12345',
  benefits: ['aa', 'bb']},
]

I want to loop the data inside the benefits, but it doesn't work because v-for needs a key and in my case, there's no key for that. Is there any other way to loop this kind of data? Thank you

2 Answers 2

2

you can use v-for inside v for :

var app = new Vue({
  el: '#app',
  data: {
    service: [{
        title: 'blablabla',
        price: '123',
        benefits: ['a', 'b']
      },
      {
        title: 'blaaablabla',
        price: '12345',
        benefits: ['aa', 'bb']
      },
    ]
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<div id="app">
  <div v-for="(item, i) in service" :key="i">
    <p>{{item.title}}</p>
    <p>My Benefits :</p>
    <p v-for="(benefit, index) in item.benefits" :key="index">
    {{benefit}}
    </p>
  </div>
</div>

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

Comments

0

You could flatten benefits and make it a computed property, then iterating through it would be much easier

var app = new Vue({
  el: '#app',
  data: {
    service: [{
        title: 'blablabla',
        price: '123',
        benefits: ['a', 'b']
      },
      {
        title: 'blaaablabla',
        price: '12345',
        benefits: ['aa', 'bb']
      },
    ]
  },
  computed: {
    benefits: function() {
      return this.service.flatMap(({
        benefits
      }) => benefits)
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<div id="app">
  <div v-for="(benefit, i) in benefits" :key="i">
    <p>{{benefit}}</p>
  </div>
</div>

1 Comment

thank you for your answer! it actually works for me! actually, i'm creating a few cards, and each card has their own benefits. but, your answer prints all the benefits from every object. apart from that, thank you and i'll look into flatmap :)