如何使用JavaScript在对象数组中执行计算

时间:2019-05-09 04:02:24

标签: javascript jquery arrays object

我正在用javascript的嵌套对象数组执行计算。 我有两个输入,如图所示

obj 如果obj.rate > mr然后

cr = (((obj.amount * obj.rate) - (obj.amount * mr))/(obj.amount * obj.rate))*100 + "%", totalcost = (obj.netfee-(cr*amountwithfee)

如果obj.rate < mr那么

cr = (((obj.amount * mr) - (obj.amount * obj.rate))/(obj.amount * mr))*100 + "%", totalcost = (obj.netfee+(cr*amountwithfee)

如何在下面的函数中精确地进行上述计算

  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);

输入

  var mr = 0.5;
  var obj =[{
    amount: 1000,
    fee: 5,
    payfee:2,
    rate:0.49
  }]

预期输出:

  result = [{
    amount: 1000,
    fee: 5,
    payfee: 2,
    netfee: 7, 
    amountwithfee: 993,
    rate: 0.49,
    cr : -2%, 
    totalcost: 26.86
  }]

2 个答案:

答案 0 :(得分:0)

//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);

答案 1 :(得分:0)

进行数学计算时,在需要的地方使用parseInt()parseFloat()或在操作中使用eval()