I'm new to js, sorry if I describe it not well enough to understand where I struggle, it's really not easy to explain what I need.
I have computed function where use reduce method to loop my objects, make some calculations inside of loop to find new variables and return array with summed values.
I know how to return sum of value inside of the loop but for only one variable, I don't know how to return 2 variables from computed, that's why I think to turn this 2 values into array and return sum somehow, to use this 2 values in future calculations. Please tip me, where to dig. My code explain the issue better:
new Vue({
el: "#demo",
data() {
return {
objects: {
price: 0,
amount: 0,
percent: 0,
fee: 0,
solution_cost: {dry:0, wet: 0}
},
},
computed: {
solutionCost() {
//Looping thru my objects
const total = this.objects.reduce((sum, object) => {
solution_cost_dry = object.amount / object.price;
solution_cost_wet = object.solution_cost[dry] * object.percent;
// Don't undestand how to get sum vor "dry" and "wet" and put it summed into array
return object.solution_cost: sum + {dry:solution_cost_dry, wet:solution_cost_wet }
}, 0)
//return array with summed values {dry:solution_cost_dry, wet:solution_cost_wet }
return total[];
},
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
答案 0 :(得分:1)
我已在更改逻辑的代码中添加了 // CHANGE 注释。您需要传递要返回的初始对象,然后更新总计的嵌套键。
computed: {
solutionCost() {
//Looping thru my objects
const total = this.objects.reduce((sum, object) => {
solution_cost_dry = object.amount / object.price;
solution_cost_wet = object.solution_cost[dry] * object.percent;
//CHANGE: add the values to the totals
sum.dry += solution_cost_dry;
sum.wet += solution_cost_wet;
return sum;
}, {dry:0, wet:0}) //CHANGE: Make the initial "sum" be the object with each key with a zero value
//return array with summed values {dry:solution_cost_dry, wet:solution_cost_wet }
return total;
},
}