如何合并并向嵌套数组对象添加其他属性

时间:2019-05-08 08:25:52

标签: javascript jquery arrays object

如何将已经存在的属性合并到嵌套数组对象中,以及如何使用javascript向该对象添加其他属性。

我有两个对象作为输入,其中apidata中对应的ID, 覆盖对象中已经存在的值,并通过注释将其他属性添加到对象,如图所示
我尝试使用下面的方法,卡住了

obj.static.forEach(e => {
  if (e.id === 'trans') {
    Object.assign(e, apidata);
    e.amount = e.srcamount - e.fee - e.payFee;
    e.netFee = e.fee + e.paymentInFee;
    e.taramount = (e.srcamount - e.fee - e.payFee) * e.rate;
  }
});

输入:

var obj = {
  static: [{
    ctob: [{
      id: "trans",
      in: "credit",
      out: "bank",
      fee: 2,
      payFee: 10,
      netfee: 12, // (fee+payfee)
      rate: 0.5,
      srcamount: 400,
      source: "SG",
      target: "TH",
      amount: 388, //(amount-netfee)
      taramount: 194 //(amount*rate)
    }, {
      id: "fund",
      in: "credit",
      out: "bank",
      fee: 1,
      payFee: 8,
      netfee: 9, // (fee+payfee)
      rate: 0.5,
      srcamount: 400,
      source: "SG",
      target: "TH",
      amount: 391, //(amount-netfee)
      taramount: 195.5 //(amount*rate)
    }]
  }, {
    btob: [{
      id: "trans",
      in: "bank",
      out: "bank",
      fee: 0,
      payFee: 5,
      netfee: 5, // (fee+payfee)
      rate: 0.5,
      srcamount: 400,
      source: "SG",
      target: "TH",
      amount: 395, //(amount-netfee)
      taramount: 197.5 //(amount*rate)
    }, {
      id: "fund",
      in: "bank",
      out: "bank",
      fee: 0,
      payFee: 6,
      netfee: 6, // (fee+payfee)
      rate: 0.5,
      srcamount: 400,
      source: "SG",
      target: "TH",
      amount: 394, //(amount-netfee)
      taramount: 197 //(amount*rate)
    }]
  }]
}

var apidata = {
  srcamount: 400,
  source: "SG",
  target: "TH",
  fee: 14,
  rate: 4.97587
}

预期输出:

result = [{
  ctob: [{
    id: "trans",
    in: "credit",
    out: "bank",
    fee: 14,
    payFee: 10,
    netfee: 24, // (fee+payfee)
    rate: 4.97587,
    srcamount: 400,
    source: "SG",
    target: "TH",
    amount: 376, //(amount-netfee)
    taramount: 1,
    870.92 //(amount*rate)
  }],
  btob: [{
    id: "trans",
    in: "bank",
    out: "bank",
    fee: 14,
    payFee: 5,
    netfee: 19, // (fee+payfee)
    rate: 4.97587,
    srcamount: 400,
    source: "SG",
    target: "TH",
    amount: 381, //(amount-netfee)
    taramount: 154.24 //(amount*rate)
  }]
}]

0 个答案:

没有答案