[英]How to perform calculation in object array using javascript
I am performing calculation in nested object array in javascript. 我在javascript中执行嵌套对象数组中的计算。 I have two inputs as shown 我有两个输入,如图所示
for the obj
if obj.rate > mr
then 对于obj
如果obj.rate > mr
那么
cr = (((obj.amount * obj.rate) - (obj.amount * mr))/(obj.amount * obj.rate))*100 + "%", totalcost = (obj.netfee-(cr*amountwithfee)
if obj.rate < mr
then 如果obj.rate < mr
那么
cr = (((obj.amount * mr) - (obj.amount * obj.rate))/(obj.amount * mr))*100 + "%", totalcost = (obj.netfee+(cr*amountwithfee)
How to do the above calculation in below function in precise manner 如何以精确的方式在下面的功能中进行上述计算
var result = obj.forEach(e=>{
..obj,
netfee: obj.fee + obj.payfee,
amountwithfee: obj.amount-obj.netfee,
cr: (((obj.amount * mr) - (obj.amount * obj.rate))/(obj.amount * mr))*100 + "%",
totalcost: (obj.netfee+(cr*amountwithfee);
})
console.log(result);
Inputs 输入
var mr = 0.5;
var obj =[{
amount: 1000,
fee: 5,
payfee:2,
rate:0.49
}]
Expected output: 预期产量:
result = [{
amount: 1000,
fee: 5,
payfee: 2,
netfee: 7,
amountwithfee: 993,
rate: 0.49,
cr : -2%,
totalcost: 26.86
}]
//initiallizing var mr = 0.5; var obj =[ { amount: 1000, fee: 5, payfee:2, rate:0.49 }, { amount: 1000, fee: 5, payfee:2, rate:0.5 } ]; var result = []; //start calculation obj.forEach(x => { let netfee = 0; let amountwithfee = 0; let cr = 0; let totalcost = 0; netfee = x.fee + x.payfee; amountwithfee = x.amount- netfee; //write your login if (x.rate < mr) { cr = (((x.amount * mr) - (x.amount * x.rate))/(x.amount * mr))*100; totalcost = (netfee + (cr * amountwithfee)); } else { cr = (((x.amount * x.rate) - (x.amount * mr))/(x.amount * x.rate))*100; totalcost = (netfee - (cr * amountwithfee)); } //generate output result.push({ 'amount': x.amount, 'fee': x.fee, 'payfee': x.payfee, 'netfee': netfee, 'amountwithfee': amountwithfee, 'rate': x.rate, 'cr': cr + "%", 'totalcost': totalcost }); }); console.log(result);
在进行数学计算时,在任何需要的地方使用parseInt()
和parseFloat()
,或者使用eval()
进行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.