How can you switch the property of an object within a VueJS array?

I'm currently working on developing a user feedback form that allows users to rate the quality of the food items they have ordered. I have an array called foodItems that displays the list of available food items along with predetermined reactions. My goal is to create a method where users can provide feedback by selecting only one reaction at a time. For example, for Pizza, they can choose to be either satisfied or dissatisfied, and their selected reaction should be highlighted accordingly. However, I'm unsure about how to implement this feature.

You can view a sample of my code on codepen.

Here's an example of how it works:

new Vue({
  el: "#app",
  data() {
    return {
      reaction: false,
      selectedReaction: "",
      foodItems: [{
          name: "Pizza",
          value: "pizza"
        },
        {
          name: "Pasta",
          value: "pasta"
        }
      ]
    };
  },
  methods: {
    setReaction() {
      this.reaction = !this.reaction;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6b1d1e0e1f020d122b5a455e455a5f">[email protected]</a>/dist/vuetify.min.js"></script>
<link rel="stylesheet"  href='https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons'>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="691f1c0c1d000f102958475c47585d">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet" />

<div id="app">
  <v-app id="inspire">
    <v-container>
      <v-layout row wrap justify-center>
        <v-flex xs6 v-for="(food,index) in foodItems" :key="index">
          <h1>{{ food.name }}</h1>
          <v-icon large left :color="reaction ? 'primary' : ''" @click="setReaction">sentiment_dissatisfied</v-icon>
          <v-icon large :color="reaction ? 'primary' : ''" @click="setReaction">sentiment_very_satisfied</v-icon>
        </v-flex>
      </v-layout>
    </v-container>
  </v-app>
</div>

Essentially, I want to enable users to rate the food items through this functionality. Any assistance would be greatly appreciated. Thank you!

Answer №1

Various strategies can be employed, but ultimately the key is to store ratings for each food item.

In my own implementation, I have set up an array called selectedReaction, which holds values of either 1, -1, undefined. Whenever a rating is added for a particular food item, I assign 1 for positive feedback and -1 for negative feedback at the corresponding index in both the foodItems and selectedReaction arrays.

<div id="app">
<v-app id="inspire">
    <v-container>
    <v-layout row wrap justify-center>
        <v-flex xs6 v-for="(food,index) in foodItems" :key="index">
        <h1>{{ food.name }}</h1>
        <v-icon large left :color="selectedReaction[index] === -1 ? 'primary' : ''" @click="setReaction(index, false)">sentiment_dissatisfied</v-icon>
        <v-icon large :color="selectedReaction[index] === 1 ? 'primary' : ''" @click="setReaction(index, true)">sentiment_very_satisfied</v-icon>  

        </v-flex>
    </v-layout>
    </v-container>
</v-app>
</div>


new Vue({
    el: "#app",
    data() {
    return {
        selectedReaction: [],
        foodItems: [
        {
            name: "Burger",
            value: "burger"
        },
        {
            name: "Salad",
            value: "salad"
        }
        ]
    };
    },
    methods: {
    setReaction(index, isSatisfied) {
        const reaction = [...this.selectedReaction];
        reaction[index] = isSatisfied ? 1 : -1;
        this.selectedReaction = reaction;
    }
    }
});

Answer №2

To simplify the process, you can utilize a boolean value such as isSatisfied. This value is set to false if the user is dissatisfied, true if they are satisfied, and undefined if no information has been provided.

However, a potential issue arises when using if(isSatisfied), as the code will go to the else block if the flag is undefined. To avoid this, you should consider implementing the following:

if(isSatisfied)
     //satisfied
if(isSatisfied === false)
     //unsatisfied

Alternatively, you could opt for a string approach by storing a string variable called feedback, which can take on values like 'satisfied', 'unsatisfied', or remain undefined.

The same concept can also be achieved using a number.

These latter options offer more flexibility since you can enhance the feedback system without altering the underlying model (within certain constraints).

It's important to note that these flags/strings/numbers need to be stored somewhere. One suggestion would be creating a new array of objects dedicated to feedback, with each object containing:

  • Food reference

  • User reference

  • User rating

Answer №3

It is crucial to ensure that every food item has an appropriate reaction attributed to it by including a reaction/feedback property for each one. It's important to observe how feedback varies between individual items. Keep in mind that there are numerous other potential strategies to consider.

    Explore more on this topic here: https://codepen.io/pjain-techracers/pen/abvXPwK

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

Exploring the initial output in JavaScript

I'm attempting to include the following body in JSON format. However, it seems that only one value is being added. json = { "Myname":"Nate", } Here is the code I'm trying to add: Body = Myproperty: [{ "vehicle": "car", "color": "Red" }, { ...

Encountered an error: Unable to access property '0' of an undefined variable

Below is the script I am using: <script> var count; var obj; function search() { xhr = new XMLHttpRequest(); xhr.open("GET", "test.json", true); xhr.send(null); xhr.onreadystatechange = function() { if (xhr.readyState == 4 & ...

Error in Vuex store: the callback provided is not a valid function

What could be causing the error message saying "callback is not a function" to appear in this particular action within my Vuex store? updateRemoteUser: ({ state, commit }, callback) => { const user = state.user axios.put(`/users/${user.id}`, { ...

Transmit form data via Ajax request

Thank you for your interest. I am looking to retrieve $_POST['Division'] from a dropdown list: <select name="Division" onchange="setImage2(this);"> <option value="1">Bronze</option> <option value="2">Silver</op ...

What is causing the table to not be displayed in this Javascript program when it is used in a

I am currently experimenting with incorporating an infinite loop before the prodNum and quantity prompts to consistently accept user input and display the output in a table. Although the program is functional when executed, it fails to showcase the table ...

What is the best method for installing Raphael.js using bower?

Currently, I am attempting to incorporate Raphael.js into my project in a highly modular manner. Since Raphael has a registered bower component, utilizing that option seemed like the most logical choice. Following some instructions from the Snap.svg readm ...

Is it necessary for Webpack to package all dependent node modules with the final bundle in production mode?

It's common knowledge that when we run npm run build, React scripts utilize Webpack to create a bundle by examining the entire dependency graph (following imports) and generating a bundle.js which is then stored in the dist/build folder for production ...

Utilize the underscore method countBy to analyze the nested properties of objects within an array

When working with JavaScript, I am handling an array of objects structured as shown below: [ { "fields": { "assignee": { "email": "emailid1", "name": "name1" } } }, { "fields": { "assignee": { "e ...

Send multiple values as arguments to a jQuery function

Beginner question ahead: I'm using the jquery function loadNewPicture() to upload pictures and the progress() function to track the percentage of the upload. Everything is functioning correctly. My query relates to the variables that can be passed t ...

Using JavaScript, append a variable to the existing URL

At the moment, I am using this JavaScript code snippet to load a URL based on the dropdown selection... var orderby = jQuery('#dropdown'); var str; orderby.change(function(){ str = jQuery(this).val(); window.lo ...

Adjusting the definition of a class method in TypeScript or JavaScript

In my code, I have a class defined as follows: class A { constructor() {} myMethod() { console.log('in my method'); } } I am looking to create a method that will take in a className and methodName like so: modifyClassMethod(cla ...

Problem with implementing swipeable tabs using Material-UI in React

I'm experiencing an issue in my application with the react swipeable tabs from material-ui. I followed all the installation steps recommended in the documentation. Currently, I am encountering the error shown in the screenshot below. Could there be a ...

"Utilizing the __proto__ property in Express.js for handling request

One issue that I've encountered is with the request.body generated by the express.urlencoded() middleware. Sometimes, it adds "__proto__" at the end of the request.body object, which makes it impossible to directly use it to initialize a mongoose mode ...

Issue with Generating divs dynamically in Ionic Framework

I'm currently working on dynamically generating a board game using divs in AngularJS, like so: HTML: <div class="boardgame" ng-repeat="square in board"> <div class="square"></div> </div> JS: $scope.board = [ {value: ...

Creating a JSON object from a dictionary: Step-by-step guide

I'm new to JavaScript and I have a situation where I receive a lengthy dictionary in the browser that looks like this: {"cat": "4" , "dog": "5", "fish": "9" } I'm curious about the most effective method to convert it into a JSON object structur ...

Having trouble retrieving Firebase data to display on a React chart

I am currently utilizing ApexChartJs in my React project. However, when attempting to retrieve dynamic data from my Firebase database, it returns undefined. https://i.stack.imgur.com/8lcnz.png Below is a snippet of code from my project: import React, { u ...

Prevent tab key focus in jQuery UI autocomplete

Sharing my own answer here: Here is the HTML code I am working with: <select id="genre-select"> <option value="-1">Please select</option> <option value="1">One</option> <option value="2">Two ...

Inconsistent alignment and formatting of fields in Bootstrap jQuery form

I need assistance with creating a form that includes three input fields: first name, last name, and email. Additionally, I would like to provide users with the option to add more groups of input fields. Currently, the three fields and the button are displ ...

Tips for displaying live data in the rows of Element UI's Table

Recently, I've been working with a table that looks like this. <v-table :data="data"> <v-table-column prop="data.attribute" label="Attribute"> </v-table-column> </v-table> Instead of displaying data.attribute in the co ...

Having trouble setting the image source in HTML with Node.js

I am a beginner with nodeJS and I am having trouble setting the src attribute of an img tag in my client side html. My node server is running on port 3000 and everything works fine when I visit http://localhost:3000. Here is the code from my server.js fil ...