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