对象合并(相同的相加,不同的创建)

var cashOrderList = [
  {
    currencyCode: "code",
    amount: 100,
  },
  {
    currencyCode: "code",
    amount: 100,
  },
  {
    currencyCode: "aode",
    amount: 100,
  },
  {
    currencyCode: "bode",
    amount: 100,
  },
  {
    currencyCode: "aode",
    amount: 100,
  },
  {
    currencyCode: "code",
    amount: 100,
  },
  {
    currencyCode: "bode",
    amount: 100,
  },
];

var detailsData = cashOrderList.reduce(function(result, current) {
  var existing = result.find(function(item) {
    return item.currencyCode === current.currencyCode;
  });

  if (existing) {
    existing.amount += current.amount;
  } else {
    result.push({ currencyCode: current.currencyCode, amount: current.amount });
  }

  return result;
}, []);

console.log(detailsData);

在上面的代码中,我们使用reduce()方法遍历cashOrderList数组,并使用find()方法查找已存在的具有相同currencyCode的对象。如果找到了已存在的对象,则将当前对象的amount值累加到已存在的对象的amount上;如果没有找到已存在的对象,则将当前对象作为一个新的对象添加到结果数组result中。

最后,使用console.log()打印合并后的数组detailsData

希望这个示例能够满足你的需求!如果你还有其他问题,请随时提问。

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值