简体   繁体   English

如何从使用reduce函数计算得出的数组中返回求和数组。 Vuejs

[英]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. 我是js的新手,很抱歉,如果我对它的描述不够好以至于无法理解我在哪里挣扎,那么解释我的需求确实不容易。

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. 我有计算函数,其中使用reduce方法来循环我的对象,在循环内进行一些计算以查找新变量并返回具有求和值的数组。

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. 我知道如何在循环内返回值的总和,但是对于一个变量,我不知道如何从计算中返回2个变量,这就是为什么我认为将这2个值转换为数组并以某种方式返回总和的原因将来的计算中有2个值。 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. 我在更改逻辑的代码中添加了// CHANGE注释。 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; }, } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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