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

3

我正在 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
  }]

1
这很令人困惑,因为你正在调用 obj.forEach 但是 obj 不是一个数组。此外,forEach() 没有返回任何内容。你是从一个对象还是一个对象数组开始的? - Mark
@MarkMeyer 谢谢回复,抱歉,它是对象数组。已更新代码。 - Senthil
2个回答

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


0
在进行数学计算时,无论何时都要使用parseInt()parseFloat(),或者使用eval()进行操作。

我绝不会建议使用 eval()。这将使我能够执行任何我想要的 JavaScript 代码。 - user3119231

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接