Looping through an array in Vue using v-for and checking for a specific key-value pair

As I dive into my first Vue app, I've encountered a minor setback.

Here's my query: How can I iterate through a list of dictionaries in Vue, specifically looping through one dictionary only if it contains a certain value for a given key?

Providing some context, the project is an online shop. My goal is to cycle through the categories in the data and display the products within each category.

The data structure looks like this:

data = {

    "categories": [

        {

            "title": "Pants",

            "products": [

                {

                    "name": "Levi Strauss",
                    "price": "$49.99",

                }

            ]

        },

        {

            "title": "Sneakers",

            "products": [

                {

                    "name": "Adidas",
                    "price": "$149.99",

                }

            ]

        }, {...}

I'm struggling with targeting a nested dictionary based on a specific key/value pair. Coming from a Python background, I was hoping for a v-for syntax similar to Python's concise approach, like:

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

However, after thorough research, I haven't found such functionality documented or available in Vue. It seems I need to rethink my strategy. Some alternative options I've considered include:

1. Restructuring the JS Object

If I simplify the structure by assigning the category title as the key, I may streamline the process of accessing specific dictionaries and values.

2. Utilizing Vue Components

Although I'm not well-versed in incorporating components within Vue, another Stack Overflow suggestion pointed me in this direction. Through the Vue documentation, it appears components could be a feasible solution.


Thank you for taking the time to explore my lengthy inquiry. Your assistance is greatly appreciated. Please don't hesitate to suggest any revisions for clarity purposes.

Answer №1

To efficiently display products, you have a couple of options:

<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>

Another approach is to filter the category first using a computed property and then iterate over its products.

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

In the template, loop through the filtered products:

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

Answer №2

To optimize your code, utilize a computed property:

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

After setting up the computed property, you can easily access the data in your template like so:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The script remains static and does not alter the "href" or "div" content based on the current URL

I am having an issue with my NavMenu on my website. It is a table with images that link to product pages, and I want to change the links and names based on the language of the site. However, the script I wrote for this is not working properly. I have tried ...

Detecting a click on the same path using Vue router's beforeEach method

I have a "beforeEach" function set up on my routes. router.beforeEach((to, from, next) => { store.commit('sidebar_open', false); next(); }) Its purpose is to close the sidebar whenever any route is clicked. <router-link :key="$rout ...

disabling a submit button

I am new to coding and need help disabling a button on document load. Can someone assist me with this? Here is my current code snippet: $(document).ready(function() { setTimeout("check_user()", 250); }); Your guidance is greatly appreciated! ...

Is it possible for me to use ts files just like I use js files in the same manner?

So I recently stumbled upon TypeScript and found it intriguing, especially since I enjoy adding annotations in my code. The only downside is that I would have to change all my .js files to .ts files in order to fully utilize TypeScript's capabilities. ...

What is preventing the specific value in React state from being updated?

Starting off as a beginner, but I'm giving it a shot: In my React project, users input landing pages and I aim to extract data from these pages using JQuery and RegEx, then update the state with the extracted value. The issue I'm facing is that ...

Using the Vuex getter to populate a component with data using the v-for directive

I am currently constructing a vue2 component, utilizing a vuex store object. The structure of the component is as follows: <template> <ul id="display"> <li v-for="item in sourceData()"> {{item.id}} </li ...

Kartik's gridview in yii2 has a unique feature where the floating header in the thead and tbody are

I'm looking to create a table gridview with a floating header, where the tbody and thead are not the same. The image appears after refreshing the page, before the modal is refreshed. After refreshing the modal, this modal is inside pjax and it sets t ...

I am confused about the process of mounting components

Utilizing pattern container/representational components, I have a CardContainer component that retrieves data from a server and passes it to a Card component. Container Component: class CardContainer extends Component { state = { 'ca ...

Tips for maintaining JSON data in CK Editor

I'm having an issue where my JSON data is not being displayed in CKEditor when using this code function retrieveRules(){ $.ajax({ url: "api", type: "POST", data: { version:'0.1' }, ...

Decode the string containing indices inside square brackets and transform it into a JSON array

I have a collection of strings that contain numbers in brackets like "[4]Motherboard, [25]RAM". Is there a way to convert this string into a JSON array while preserving both the IDs and values? The desired output should look like: {"data":[ {"id":"4","i ...

Activate lighting in Three.js with a simple click

I successfully loaded a sphere mesh with Lambert material. Now, I am trying to add a light source to the point where there is an intersection after clicking. target = object that was clicked. to = vector3 of my click. When the dblclick event listener is ...

Leveraging summernote in meteor with Discover Meteor tutorial

Recently, I've been delving into the world of Discover Meteor and encountering some challenges along the way. My current hurdle involves integrating content entered in summernote into mongo, but it seems to be more complicated than expected. The fil ...

Error: Unable to authenticate due to timeout on outgoing request to Azure AD after 3500ms

Identifying the Problem I have implemented SSO Azure AD authentication in my application. It functions correctly when running locally at localhost:3000. However, upon deployment to a K8s cluster within the internal network of a private company, I encounte ...

How can I obtain the model values for all cars in the primary object?

const vehicles={ vehicle1:{ brand:"Suzuki", model:565, price:1200 }, vehicle2:{ brand:"Hyundai", model:567, price:1300 }, vehicle3:{ brand:"Toyota", model ...

Retrieve a prepared response from a TypeORM query

I need to retrieve all the courses assigned to a user with a simple query: There are 2 Tables: students & courses return await this.studentsRepository .createQueryBuilder('s') .leftJoinAndSelect('courses', 'c' ...

Navigating the world of cryptocurrency can be daunting, but with the right tools

Hello fellow developers, I've encountered some difficulties with cryptocurrency in my Nativescript project. I am attempting to incorporate the NPM package ripple-lib into my code, but I have been unsuccessful using nativescript-nodeify. How can I suc ...

Check the email for accuracy and show as needed

I need help verifying email validity in JavaScript and displaying an alert box if it's invalid. If the email is valid, I want to display div2 instead. However, my current code doesn't seem to be working as expected. Below is the JavaScript code ...

Ensuring consistency of variables across multiple tabs using Vue.js

In my vuejs front-end, a menu is displayed only if the user is logged in. When I log out, the variable isLogged is updated to false, causing the menu to hide. If I have multiple tabs open with the frontend (all already logged in) and I logout from one tab ...

Loop through a collection of items based on the values in a separate array using jQuery

I have a list of objects below The newlist and SelectID array are both dynamic. I am populating through a function, now I need to iterate and create the new list. var newList = [ { id : 1,name="tea",plant:"darjeeling"}, { id : 2,name="cof ...

restructure array upon alteration of data

Here's the current structure of an array stored in a $scope variable: $scope.objects: [ {selected: true, description: 'string1'}, {selected: false, description: 'string2'}, {selected: true, description: 'string3'}, ...