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

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

There are two arrays:

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


        
5条回答
  •  隐瞒了意图╮
    2020-12-19 14:57

    Version with additional object keys. The body of the function does not interfere with what object has properties. So sum by "qty" and check by "prop"

    var first = [ 
      {quantity:100, id:1, variantId: 1}, 
      {quantity:300, id:2, variantId: 2, propA: 'aaa'},
    
    ];
    
    var second = [
      {quantity:100, id:1, variantId: 1},
      {quantity:200, id:2, variantId: 2, propB: true}, 
      {quantity:300, id:3, variantId: 3, propC: 'ccc'}, 
    ]
    
    function mergeArrays(arrayOfArrays, propToCheck, propToSum) {
        let sum = [];
        [].concat(...arrayOfArrays).map(function(o) {
            
            let existing = sum.filter(function(i) { return i[propToCheck] === o[propToCheck] })[0];
        
            if (!existing) {
    
                sum.push(o);
            } else {
    
                existing[propToSum] += o[propToSum];
                
                let copyProps = Object.keys(o).filter(obj => {
                      return existing[obj] !== o[obj]
                }).map(val => (val !== propToSum) ? existing[val] = o[val] : null)
            }
                 
        });
    
        return sum;
    }
    
    console.log(mergeArrays([first, second], 'variantId', 'quantity'))

提交回复
热议问题