Searching and updating a value in an array using JavaScript

I need help solving a Javascript issue I'm facing. I'm working on an e-commerce project built in Vue, and I want to implement the selection of product variants on the client-side. The data format being sent to the backend looks like this:

{
    "options": [
        {
            "key": "Size",
            "value": "L"
        },
        {
            "key": "Color",
            "value": "Green"
        }
    ]
}

The backend responds with the price of the selected options, and the product ID is retrieved from the URL. To capture the selected options on the frontend, I am using the following code snippet:

getVariationPrice(id, attr, value){
            this.variation.options.push({
                    key: attr,
                    value: value
        });

In this function, 'id' represents the product ID taken from the URL.

To display the attributes for each product, I have implemented the markup as follows:

 <span v-for="(attributes, index) in product.attributes" :key="index">
         {{ attributes.key }}
    <v-chip-group active-class="deep-purple accent-4 white--text" column>
       <span v-for="(values, vIndex) in attributes.values" :key="vIndex">
         <v-chip  @click="getVariationPrice(product.id, attributes.key, values)">{{ values }}</v-chip>
       </span>
    </v-chip-group>
  </span>

The issue arises when selecting values, causing them to be appended to the array incorrectly. I'm looking for a way to make these values replaceable, considering that the backend may return different attribute keys and values, not limited to just size and color. The backend must only return the selected keys and values.

PS: Keep in mind that the backend may provide a variety of attributes, and it will verify each given value before searching for the product. The returned data should include only the selected keys and values.

Answer №1

Using v-model with v-chip-group in Vuetify can simplify your code.

<v-chip-group v-model="selectedItems" multiple></v-chip-group>

Make sure to assign a value to each chip for proper functionality.

No need to manually handle click events, v-model will take care of updating the selected items automatically.

I hope this tip proves useful!

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

SetBootstrapTooltip at the location of the mouse pointer

Is it feasible to implement a bootstrap tooltip that follows the mouse cursor in AngularJS? If not, what other options are available for achieving this functionality? ...

What is the best way to configure a metered subscription plan on Stripe that invoices annually but bills extra fees for overage on a monthly basis

I'm in the process of setting up a subscription system on stripe that includes a plan with 5000 monthly credits for a flat $299 yearly fee. My goal is to charge customers who exceed their monthly credit limit by the end of each month. For example, if ...

Every time I attempt to destructure the state object in react typescript, I encounter the error message stating 'Object is possibly undefined'

Whenever I attempt to destructure my state object in react typescript, I encounter an error stating Object is possibly 'undefined'. When I try using optional chaining, a different error pops up saying const newUser: NewUser | undefined Argument o ...

Failed to retrieve the requested item using fetch, encountering a NetworkError

My API is being accessed to retrieve data using this code snippet. It sends the email and password to the API: onSubmitSignIn = () => { fetch('http://localhost:3001/signin', { method: 'post', headers: {'Content-Type&ap ...

Fetching deeply nested data from JSON within Angular Material tables - ANGULAR

Having trouble retrieving data from localhost, especially when it's in a different structure. Any suggestions on how to properly extract and display this data for the user? This is my attempted approach, but I'm encountering an error message: ER ...

Struggling to access specific data within a JSON object? Wondering how to extract and display data from a JSON object in VUE?

Despite my extensive searching on Stack and the internet, I have not been able to find a solution to my problem. Currently, I am attempting to retrieve data from a JSON file located in the Vue src folder. The file contains three arrays with names that inc ...

Pressing the button will allow you to select and copy the text within the

I am looking to incorporate a mock-chat feature into my website. The concept is to type something on the website, then click a button next to it which will move the text to a frame above. I attempted this using a textarea and even found a code for selectin ...

Having trouble getting the "If paused" feature to function properly in videojs

When my video is paused, I want to display an overlay on top of it. I found the following piece of code in the documentation: var isPaused = myPlayer.paused(); var isPlaying = !myPlayer.paused(); So, I tried implementing it like this: var isPaused = m ...

Maximizing the efficiency of React.js: Strategies to avoid unnecessary renders when adding a new form field on a webpage

Currently, I have a form that consists of conditionally rendered fields. These components are built using MUI components, react-hook-form, and yup for validation. In addition, within the AutocompleteCoffee, RadioBtnGroup, and TxtField components, I have i ...

Explore the Benefits of Using MUI V5 Grid Component for Your Box Design

Exploring MUI to delve into the world of React for the first time. Curious about the usage of the Box component alongside the Grid component. The example on the docs showcases this scenario. export default function BasicGrid() { return ( <Box sx={ ...

Tips for retrieving return values from an ajax form submission

When using ajax to submit a form, I encountered an issue where the process would halt at api.php and not return to the ajax success. Below is the code snippet: <form method="POST" id="form_1" action="../api.php" enctype="multipart/form-data" novalidate ...

Encountering issues when implementing react-router with the client-side library

After following the author's suggestion, I've successfully loaded the client-side library. The recommended method is to simply drop a <script> tag in your page and use the UMD/global build hosted on cdnjs. I have ensured that ReactRouter i ...

Issue with implementing MUI Style Tag in conjunction with styled-components and Typescript

I have created a custom SelectType component using Styled Components, which looks like this: import Select from '@mui/material/Select'; export const SelectType = styled(Select)` width:100%; border:2px solid #eaeaef; border-radius:8px ...

What is the best way to split a semicircular border radius in two equal parts?

Is there a way to halve the yellow line or remove it from above the red box, while keeping it below? Can this be achieved using just HTML and CSS, or is JavaScript necessary? * { margin: 0; padding: 0; box-sizing: border-box; } body { height: 1 ...

Execute the command "prisma migrate dev" to update the existing database

I'm currently in the process of configuring Prisma migrate on a pre-populated MySQL database in my development environment, but I'm facing challenges getting it to function correctly. 1. After executing prisma db pull successfully to generate th ...

The success callback in JQuery Ajax does not function properly when constructing an array of Ajax calls

I am facing a challenge in building an array of custom objects by resolving promises from an array created based on another array. Consider having an array of letters = ['a', 'b', 'c']. I then map this array to make Ajax call ...

Exploring innovative designs for asynchronous JavaScript programming

Imagine you have an Express app and you need to retrieve data from a database to display on the frontend. There's a function in your code that looks like this (using node-mysql for handling database queries) exports.getData = function() { ...

I'm puzzled as to why, but my code seems to be causing an issue with the command prompt, possibly due

Recently, I've been taking on the challenges of Advent of Code. Day 2 has me stumped, as there's a peculiar issue with the code when running it through node.js in the command prompt: const fs = require("fs"); var valid = fs.readFileSync("inpu ...

Ways to protect my login details when making an ajax request?

The scenario I am dealing with is as follows: I have developed a website using Javascript where users are required to input a username and password. Subsequently, the site makes an ajax call to the Webserver. On the other end, I have a PHP-powered Webser ...

What is the best way to transform a one-dimensional object array into a two-dimensional array in a Vue component, based on a specific key?

My vue modules are structured like this: [types.GET_PRODUCT_CATEGORIES] (state,{ stores }) { state.product_categories = {} console.log(stores); stores.forEach(message => { set(state.product_categories, message.id ...