[Vuejs]-Vue: v-for loop through array if it has specific key:value pair

4👍

you can use a nested loop:

<div v-for="category in categories" v-if="category.title === 'Sneakers'">
    <div v-for="product in category.products">
        <p>{{ product.name }}</p>
        <p>{{ product.price }}</p>
    </div>
</div>

or filter your category first in a computed property and then loop through it products.

computed: {
    myProducts() {
        return this.categories.filter( ( category ) => { 
             return category.name === 'Sneakers';
        })[ 0 ].products;
    }
}

In the template loop though the products:

<div v-for="product in myProducts">
     <p>{{ product.name }}</p>
     <p>{{ product.price }}</p>
</div>

4👍

Use a computed property:

computed: {
  sneakerProducts() {
    return this.data.find(category => category.title === 'Sneakers').products;
  }
}

then from your template you can do:

<div v-for="sneaker in sneakerProducts">
    <p>{{ sneaker.name }}</p>
    <p>{{ sneaker.price }}</p>
</div>

Leave a comment