简体   繁体   中英

How to return summed array from computed using reduce function. Vuejs

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> 

I've added //CHANGE comments to the code where I changed logic. You need to pass in an initial object of what you want to return, and update the nested keys for the totals.

 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; }, } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM