Tanja K.
Tanja K.

Reputation: 33

Vue JS: Looping through object inline attribute

I am new to vue.js so this might be an easy question, but I unfortunatelly didnt come to a result on my own.

So this is the basis of my template:

<template v-for="page in $props.data.pageInfo" >
  <div class="overviewItem" :key="page.uid" :data-cat=" **looping through the object to get both cat_id's ** ">
    <div v-for="(cat, index) in page.categories" :key="index" >
      <p v-if="index === 0" class="subtitle">
        {{ cat.title }}
      </p>
    </div>
  </div>
</template>

{{ page.categories }} has the following values at the first .overviewItem:

[
{
  "cat_id": 1,
  "title": "Kategorie 1"
},
{
  "cat_id": 2,
  "title": "Kategorie 2"
}
]

The loop to get the subtitle works perfectly fine, but I cannot find any option on how to loop through this object so that i get the two values of data-cat attribute.

Upvotes: 1

Views: 371

Answers (1)

Dan
Dan

Reputation: 63129

Use .map to generate a new array of just the cat_id and then join them together with a space in between:

<div
   class="overviewItem"
   :key="page.uid"
   :data-cat="page.categories.map(c => c.cat_id).join(' ')"
>
...
</div>

Upvotes: 1

Related Questions