Building an instance using an object and an array with Vue.js 2.0

I am working with an array and an object created in Vue.js, and my goal is to combine them into a single 'selection' array following this format:

selection[
{food: Chicken, quantity: 3},
{food: Rice, quantity: 2},
{food: Pasta, quantity: 1}
];

Here is the code I have set up to achieve this:

var selection = []

for (var i = 0; i < meals.length; i++) {
    selection.push({
        food: this.meals[i],
        quantity: creditsPerMeal[meals[i]]
    });
}

Although I am encountering a Syntax error, I believe that I am very close to the solution. However, I am reconsidering if this should be part of the data structure.

Below is the complete code snippet:

<template>
  <div>
    <div>Credits available: {{ credits }}</div>
    <div v-for="meal in meals">
      {{meal}}
      <input :id="meal" :name="meal" v-model.number="creditsPerMeal[meal]" type="number">
    </div>
    <div>
      Total Credits Used: {{creditsSum}}
    </div>
  </div>
</template>

<script>
  export default {

    mounted() {
        console.log('Component ready.');

        console.log(JSON.parse(this.f));

    },

    props: ['f','c'],

    name: 'credits',
    data: function () {
     var meals = JSON.parse(this.f)

      var creditsPerMeal = {}
      for (var i = 0; i < meals.length; i++) {
        creditsPerMeal[meals[i]] = 0
      }

      var selection = []

      for (var i = 0; i < meals.length; i++) {
          selection.push({
              food: this.meals[i],
              quantity: creditsPerMeal[meals[i]]
          });
        }

      return {
        credits: this.c,
        meals,
        selection,
        creditsPerMeal
      }
    },
    computed: {
      creditsSum () {
        return Object.values(this.creditsPerMeal).reduce((a, b) => a + b, 0)
      }
    }
  }
</script>

UPDATE

When looking at the image below, you can see that while creditsPerMeal updates upon input, the 'selection' array does not update. How can I bind these two together properly?

https://i.stack.imgur.com/hObgb.png

Edited computed:

computed: {
  creditsSum () {
    return Object.values(this.creditsPerMeal).reduce((a, b) => a + b, 0);
  },

  createSelection: function (){
    for (var i = 0; i < meals.length; i++) {
       return createSelection.push({
          food: meals[i],
          quantity: creditsPerMeal[meals[i]]
      })
      }
  }
}

Answer №1

There is a clear syntax error in the line "selection=," that you need to address:

return {
    credits: this.c,
    meals,
    selection=,
    creditsPerMeal
  }

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

Prevent the hover() effect from affecting all div elements at once

I am aiming to achieve a function where hovering over a div with the "rectangle" class will display another div with the "description" class. Initially, the description div will have a display value of "none", but upon hovering, it should become visible. ...

The jQuery autocomplete feature seems to be malfunctioning as no suggestions are showing up when

I am currently generating input text using $.each: $.each(results, function (key, value) { if (typeof value.baseOrSchedStartList[i] != 'undefined') { html += "<td><input type='te ...

How to automatically scroll to the bottom using jquery/css

I've recently developed a chatroom using li elements, but I'm encountering an issue where the chat doesn't stick to the bottom once it reaches a certain number of messages. I suspect it has something to do with the height settings, but I can ...

Definition for TypeScript for an individual JavaScript document

I am currently attempting to integrate an Ionic2 app within a Movilizer HTML5 view. To facilitate communication between the Movilizer container client and the Ionic2 app, it is crucial to incorporate a plugins/Movilizer.js file. The functionality of this f ...

How to extract a one-of-a-kind identification number from the browser using just JavaScript in a basic HTML file?

Is there a way to obtain a distinct identification number from a browser without resorting to techniques such as generating and storing a unique number in cookies or local storage, and without utilizing a server-side language? ...

Error: VueQuill Vue3 encountered an issue while trying to read properties of undefined with the message "emit"

Incorporating VueQuill into my vue3 application is resulting in the following console error when attempting to display an HTML string - https://i.stack.imgur.com/KGQqD.png This is my code snippet: <template> <div class=""> & ...

Leveraging CSS or JavaScript for Displaying or Concealing Vacant Content Sections

I'm working on developing a page template that utilizes section headers and dynamically pulled content from a separate database. The current setup of the page resembles the following structure: <tr> <td> <h3> ...

Steps to prevent specific links from being clickable in React Native's webview component

In my React Native app, I am utilizing the react-native-webview component to display blog posts. The code I have implemented is straightforward, but my goal is to restrict the webview to only show content from the blog section of the website, preventing us ...

What is the best way to manage errors and responses before passing them on to the subscriber when using rxjs lastValueFrom with the pipe operator and take(1

I'm seeking advice on the following code snippet: async getItemById(idParam: string): Promise<any> { return await lastValueFrom<any>(this.http.get('http://localhost:3000/api/item?id=' + idParam).pipe(take(1))) } What is the ...

Error: When attempting to utilize the Image-Slider, an issue arises with reading the property 'classList' which is undefined

I am currently in the process of developing a website using Strapi as my CMS and Next.js(React) for the frontend. The website features an image slider that includes images, headlines, and descriptions. However, I have encountered an issue where after spen ...

Requests in Node.js may unexpectedly stall and remain unresolved until the server is restarted

I've encountered a strange and seemingly sporadic issue with our web application that I can't seem to resolve through debugging. The app runs smoothly for varying durations, ranging from 10 minutes to 6 hours, but then all of a sudden, any remote ...

Searching recursively for keys with empty values in an array using Javascript

I've written a function that recursively locates empty values in a nested array. The function initially produces the correct value, but it seems to reset it to the input value before returning the result. What could I be overlooking? Below is my co ...

Looking to transform this PHP function into a jQuery function that generates all the possible combinations of values in an array?

I stumbled upon this PHP code on a programming forum. Here's the original code snippet: function everyCombination($array) { $arrayCount = count($array); $maxCombinations = pow($arrayCount, $arrayCount); $returnArray = array(); $conve ...

Non-responsive Click Event on Dynamically Created Div Class

I am facing some uncertainty in approaching this problem. In the HTML, I have created buttons with additional data attributes. These buttons are assigned a class name of roleBtn. When clicked, they trigger the jQuery function called roleBtnClicked, which ...

What steps can I take to ensure that my React child components will render successfully, even if a prop is absent

TLDR; Seeking solution to render child components in React even if a property of this.props is missing. My React app utilizes Yahoo's Fluxible and fetches data from a Wordpress site using WP REST API. Sometimes, the API may return incomplete data cau ...

Display information from a mysql database table within a selection menu

Currently, I am working on a dropdown menu that should display data from a MySQL table. However, I am facing an issue which is outlined below: In my PHP script, I have approached it in the following manner: <label class="col-form-label" for="formGrou ...

Is it possible for me to move a function into a utils file and then incorporate it into a React component, all while passing a function from the component to it?

I'm in the process of moving my getFontColor() function to a utils folder in order to call it from a component. However, this function relies on another function within the component (getBgColor()). How can I pass getBgColor to the util function and t ...

What is the best way to transfer a value from state to a function as a parameter?

I have been struggling to find a way to pass the value from state (personId) as a parameter to the function (fetchPersonInfo). Despite my efforts, nothing seems to be working. That's why I decided to seek your assistance on this matter. class Page ex ...

`Issues with AJAX PHP file upload`

I've been working on an AJAX PHP upload script, but I'm facing some issues. Once the user selects an image to upload, it should display in the specific div container specified in my javascript file (which is working fine). However, I believe ther ...

the absence of any content being shown when using v-else

I'm currently delving into Vue.js and stumbled upon an unusual behavior that I couldn't find any information about on the Internet. For some reason, the DIV with v-else isn't rendering any content that I place inside it. I tried to underst ...