How to merge two arrays and sum values of duplicate objects using lodash

后端 未结 5 1606
走了就别回头了
走了就别回头了 2020-12-19 14:34

There are two arrays:

[
  {\"id\": \"5c5030b9a1ccb11fe8c321f4\", \"quantity\": 1},
  {\"id\": \"344430b94t4t34rwefewfdff\", \"quantity\": 5},
  {\"id\": \"34         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-19 14:46

    You can just do this with reduce:

    let a1 = [
      {"id": "5c5030b9a1ccb11fe8c321f4", "quantity": 2},
      {"id": "344430b94t4t34rwefewfdff", "quantity": 1}
    ];
    
    let a2 = [
      {"id": "5c5030b9a1ccb11fe8c321f4", "quantity": 1},
      {"id": "344430b94t4t34rwefewfdff", "quantity": 5},
      {"id": "342343343t4t34rwefewfd53", "quantity": 3}
    ];
    
    let result = Object.values(a1.concat(a2).reduce((acc, v) => {
       if (!acc[v.id]) {
           acc[v.id] = {id: v.id, quantity: 0};
       }
       acc[v.id].quantity += v.quantity;
       return acc;
    }, {}));
    
    console.log("Results: ", result);

提交回复
热议问题