SOURCE

function calculateTransactionValue(jsonString) {
  // 解析 JSON 字符串
  const transactions = JSON.parse(jsonString);

  // 初始化各种交易类型的变量
  let Authorization_Settled = 0;
  let TransactionFee_Settled = 0;
  let ForeignFee_Settled = 0;
  let Authorization_Authorized = 0;
  let Reversal_Settled = 0;
  let Refund_Settled = 0;
  let Authorization_Pending = 0;

  // 遍历交易并计算每种类型的金额总和
  transactions.forEach(transaction => {
    // 使用 Math.abs() 将负数转换为正数
    const amount = Math.abs(parseFloat(transaction.amount));

    switch (transaction.type) {
      case 'Authorization_Settled':
        Authorization_Settled += amount;
        break;
      case 'TransactionFee_Settled':
        TransactionFee_Settled += amount;
        break;
      case 'ForeignFee_Settled':
        ForeignFee_Settled += amount;
        break;
      case 'Authorization_Authorized':
        Authorization_Authorized += amount;
        break;
      case 'Reversal_Settled':
        Reversal_Settled += amount;
        break;
      case 'Refund_Settled':
        Refund_Settled += amount;
        break;
      case 'Authorization_Pending':
        Authorization_Pending += amount;
        break;
    }
  });

  // 使用更新后的公式计算最终值
  const result = Authorization_Settled +
    TransactionFee_Settled +
    ForeignFee_Settled +
    Authorization_Authorized -
    Reversal_Settled -
    Refund_Settled -
    Authorization_Pending;

  return result;
}
// 示例使用(假设数据中包含了新的交易类型)
const json = `
[
  {
    "type": "Authorization_Declined",
    "num": "161",
    "amount": "-103928.13"
  },
  {
    "type": "Authorization_Settled",
    "num": "813",
    "amount": "-537564.59"
  },
  {
    "type": "Authorization_Cancelled",
    "num": "32",
    "amount": "-19471.98"
  },
  {
    "type": "Authorization_Authorized",
    "num": "40",
    "amount": "-22714.90"
  },
  {
    "type": "Reversal_Settled",
    "num": "2",
    "amount": "0.00"
  }
]
`
console.log(calculateTransactionValue(json));


console 命令行工具 X clear

                    
>
console