合并多个对象数组并将重复值javascript加起来

Mat*_*van 2 javascript arrays

我有多个数组,看起来像这样

第一个对象数组看起来像这样

Array[4]

    0 : Object
        price:"2"       
        ref:"A"
    1 : Object
        price:"20"
        ref:"B"
    2 : Object
        price:"23"      
        ref:"C"
    3 : Object
        price:"23"      
        ref:"D"     
Run Code Online (Sandbox Code Playgroud)

第二个对象数组看起来像这样

Array[4]

    0 : Object
        price:"12"      
        ref:"A"
    1 : Object
        price:"5"       
        ref:"B"
    2 : Object
        price:"23"      
        ref:"E"
    3 : Object
        price:"23"      
        ref:"F" 
Run Code Online (Sandbox Code Playgroud)

我的第三个对象看起来像这样.

Array[2]

0 : Object
    name:"Blah"     
    fcp:"erol"
1 : Object
    name:"Blah2"        
    fcp:"tpep"
Run Code Online (Sandbox Code Playgroud)

现在我想的总结price基础上ref.第一个对象和第二个对象具有参考A和B的共同点.这样最终的对象看起来像

Array[7]

    0 : Object
        price:"14"      
        ref:"A"
    1 : Object
        price:"25"
        ref:"B"
    2 : Object
        price:"23"      
        ref:"C"
    3 : Object
        price:"23"      
        ref:"D" 
    4 : Object
        price:"23"      
        ref:"E"
    5 : Object
        price:"23"      
        ref:"F" 
    6 : Object
        name:"Blah"     
        fcp:"erol"
    7 : Object
        name:"Blah2"        
        fcp:"tpep"  
Run Code Online (Sandbox Code Playgroud)

Gru*_*ndy 5

您可以使用reduce功能进行灌浆

var array1 = [{
    price: "2",
    ref: "A"
  },
  {
    price: "20",
    ref: "B"
  },
  {
    price: "23",
    ref: "C"
  },
  {
    price: "23",
    ref: "D"
  }
];

var array2 = [{
    price: "12",
    ref: "A"
  },
  {
    price: "5",
    ref: "B"
  },
  {
    price: "23",
    ref: "E"
  },
  {
    price: "23",
    ref: "F"
  }
];

var array3 = [{
    name: "Blah",
    fcp: "erol"
  },
  {
    name: "Blah2",
    fcp: "tpep"
  }
];

var result = array1.concat(array2, array3).reduce(function(acc, curr) {
  if (curr.ref) {
    var fromMap = acc.map[curr.ref];
    if (!fromMap) {
      acc.map[curr.ref] = fromMap = {
        price: 0,
        ref: curr.ref
      }
      acc.result.push(fromMap);
    }
    fromMap.price += parseFloat(curr.price);
  } else {
    acc.result.push(curr);
  }
  return acc;
}, {
  map: {},
  result: []
}).result;

console.log(result);
Run Code Online (Sandbox Code Playgroud)