James Parsons
James Parsons

Reputation: 925

Creating an object from an object and an array in Vue.js 2.0

I have an array and an object created using Vue.js, I could like to combine them into one 'selection' array in the format of:

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

I have the following set up to be able to do it:

  var selection = []

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

As it stands I am getting a Syntax error but I am not convinced I should be doing this as part the data. I feel that I am pretty close.

Here is the full code:

<template>
  <div>
    <div>Credits carried through: {{ credits }}</div>
    <div v-for="meal in meals">
      {{meal}}
      <input :id="meal" :name="meal" v-model.number="creditsPerMeal[meal]" type="number">
    </div>
    <div>
      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

As you can see from the image below if I input creditsPerMeal updates but selection doesnt, how would I bind in a way that it would.

enter image description here

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]]
      })
      }
  }
}

Upvotes: 0

Views: 10751

Answers (1)

Potray
Potray

Reputation: 1998

You have indeed a syntax error in "selection=,":

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

Upvotes: 1

Related Questions