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

Error on homepage with Vue Storefront API issue

I have successfully implemented vue-storefront on . However, the standard homepage layout is not displaying correctly due to an error, most likely related to the API. There are no output errors in the terminal, all systems seem to be running smoothly wit ...

Executing an Ajax call to trigger a NodeJS function that executes a bash script

I have created a bash script to generate a JSON file that needs to be parsed and sent to the client-side JavaScript for display. My goal is to achieve this without refreshing the page and without using jQuery. I attempted to use Axios but seem to be facing ...

Navigating to a different page by clicking on a Table Row in react-table

Whenever I click on a table row, I am unable to navigate to another page. Although I have successfully implemented the getTdProps function to retrieve properties from the table row upon clicking on it, I'm facing difficulty in using 'react-route ...

Switching the default z-index for child elements within an HTML container

According to the specification, elements are typically drawn "in tree order" for in-flow, non-positioned elements of similar block level or float status and identical z-index. This means that elements declared last in the HTML markup appear on top. But wha ...

Associate a variable with a model within a controller

My goal is to bind a variable in my Controller to a model linked to an input like this: <body ng-app="myApp"> <div ng-controller="MyController"> <input type="text" ng-model="myVar1" /> {{ myVar1 }} <br /> ...

Modifying an onClick handler function within a react element located in a node module, which points to a function in a prop declared in the main Component file

I have successfully implemented the coreui CDataTable to display a table. return ( <CDataTable items={data} fields={fields} ... /> ) Everything is working smoothly, but I wanted to add an extra button in the header of the C ...

Toggle the font weight in a text area by clicking a button

I need help with creating a button that will change the font-weight to bold when clicked and then revert back to normal when un-clicked. However, I only want the specific part of the text area where the user clicks the button to be bolded, not the entire t ...

"Enhanced Laravel application incorporating Vue.js for data manipulation, utilizing Axios for API interactions

Lately, I've been diving into the world of Laravel and Vue.js. However, I've run into a roadblock while working with server-side interactions. After making a post request to the server and getting back a response, I noticed that there is an extra ...

Error: Module Not Found in Node.js

Hello everyone, I'm a newcomer to the world of JS and Node.js and I'm facing some issues while trying to set up a webdriverio project using cucumber and PageObject. Whenever I attempt to run a test, I encounter this error message: ERROR: Cannot ...

What is the significance of the source element in Vue3's audio element?

Playing mp3 files works in Vue 2, but not in Vue3. <template> <audio src="../file_example_MP3_700KB.mp3" controls ></audio> </template> In Vue3, the code needs to be modified as follows: <template> <audi ...

jQuery does not support the addition of new fields in HTML

Recently, I've been working on creating a lucky number generator. Initially, I developed it using C# and now I'm in the process of transitioning it to JavaScript and jQuery. You can view the latest version here. However, I've encountered an ...

What are the steps for implementing webpack 5 configurations in Next.js?

I can't seem to figure out how to properly add experiments to my webpack config. Here is my current environment: [email protected] [email protected] To set up, I started a new Next.js app using the command npx create-next-app blog Accord ...

Is there any assistance available for incorporating Slimbox and loading images through JavaScript?

I have exhaustively searched online for a solution to my problem, but without any luck. So now I am reaching out to the experts who know exactly what they're doing. Currently, I'm in the process of loading images from Facebook using a handy jQue ...

How can I save variable values to a text file or Excel file using Cypress.io?

Is there a way to write the values of a variable on a Text or Excel sheet? I have a variable called tex that stores string values, and I want to output these values onto text files or an Excel sheet if possible. beforeEach(() => { cy.visit('ht ...

Is the required attribute for form submission in Material UI not verifying in another file?

It seems that I may be importing incorrectly because a required field does not display a "please fill in this field" popover when attempting to submit a form. The imported classes are as follows: import * as React from 'react' import FormContro ...

Add a fresh category to a JSON document

Combining Express (Node.js) and Mongoose, I am developing a REST API and attempting to implement JWT token-based login. However, I have encountered an issue. Upon executing the code below: const mongoose = require('mongoose'); const User = mongo ...

AngularJS offers a single checkbox that allows users to select or

For my code, I need to implement a single checkbox. In my doc.ejs file: <tr ng-repeat="folder_l in folderlist | orderBy:created_date" > <td> <div class="permit"> <input class="chkbtn move_check" type="checkbox" id=" ...

Tips for leveraging pinia store with the v-for directive to maintain reactivity?

My pinia data store is set up similarly to the code below, storing user information and a list of individual orders: order.js import { defineStore } from 'pinia' import { reactive } from 'vue' export const useOrderStore = defineStore( ...

What is the functionality of this JQuery Popup?

I'm facing an issue with my JQuery Popup. When the "Login" button is clicked, it hides the Login popup but doesn't show the Sign Up popup. How can I make sure that clicking on "Login" hides the Login popup and shows the Sign Up popup accordingly? ...

Leveraging data generated by a CasperJS script within an AngularJS application

After using yeoman.io to create an angular.js single page application, I found myself with app.js managing routes, mycontroller.js scripts, and an index.html file filled with "bower_components" references for libraries installed through the command line us ...