Arrays 键入脚本合并2个数组,如果它们具有相同的id,则增加数量

Arrays 键入脚本合并2个数组,如果它们具有相同的id,则增加数量,arrays,angular,typescript,Arrays,Angular,Typescript,我正在处理Angular 8项目,我想将2个数组合并为1,如果它们在对象中具有相同的值,则增加数量。我自己试过几次,效果并不好 mergedOrderList: any[]= []; lstOldOrder: any[] = [ {id: "", products_id: "", qty: 1, ...}, {id: "", products_id: "", qty: 1, ...}, {id: "&qu

我正在处理Angular 8项目,我想将2个数组合并为1,如果它们在对象中具有相同的值,则增加数量。我自己试过几次,效果并不好

mergedOrderList: any[]= [];

lstOldOrder: any[] = [
{id: "", products_id: "", qty: 1, ...},
{id: "", products_id: "", qty: 1, ...},
{id: "", products_id: "", qty: 1, ...},];

lstNewOrder: any[] = [
{id: "", products_id: "", qty: 1, ...},
{id: "", products_id: "", qty: 1, ...},
{id: "", products_id: "", qty: 1, ...},];

lstNewOrder.forEach(newOrder => {

    let isDubplicated: boolean = false;

    lstOldOrder.forEach(oldOrder => {

      if (newOrder.products_id == oldOrder.products_id) {
        oldOrder.qty += newOrder.qty;
        isDubplicated = true;
        mergedOrderList.push(oldOrder);
      }
    });

    if (!isDubplicated) {
      mergedOrderList.push(newOrder)
    }

  });

我是这样做的,当它们都有相同的产品id时,它们工作。但是当新订单没有产品id时,它们会跳过我的旧订单,只向列表中添加新订单。我不太确定我做对了。谢谢

请看问题在于,如果 新列表项的
产品\u id
与旧列表中的任何项匹配

因此,如果
lstNewOrder

相反,你应该做的是:

将项目添加到
mergedOrderList
中,但如果存在匹配项,则增加数量

mergedOrderList = [];

lstOldOrder = [
  { id: "1", products_id: "", qty: 1 },
  { id: "2", products_id: "", qty: 1 },
  { id: "3", products_id: "", qty: 1 },
];

lstNewOrder = [
  { id: "4", products_id: "", qty: 1 },
  { id: "5", products_id: "", qty: 1 },
  { id: "1", products_id: "", qty: 1 },
];

lstNewOrder.forEach((newOrder) => {
  Oindex = -1;
  lstOldOrder.forEach((item, index) => {
    if (item.id == newOrder.id) {
      Oindex = index; // Getting the Index of that item in old array.
    }
  });

  if (Oindex != -1) { // if that item was in old Array
    newOrder.qty += lstOldOrder[Oindex].qty; // Increase Quantity in newOrderItem
    lstOldOrder.splice(Oindex, 1); // Delete that Item from OldArray
  }
  mergedOrderList.push(newOrder); // Add the Item in Merged
});

mergedOrderList.concat(lstOldOrder); // Finally add all the remaining Items
代码中的所有边缘情况都没有得到正确处理,对此表示抱歉。 请随意编辑我的答案,它可能会帮助其他人