合并多个对象数组并求和重复值javascript [英] Merge multiple array of objects and sum duplicate values javascript

查看:215
本文介绍了合并多个对象数组并求和重复值javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have multiple arrays, which looks like this

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

1st array of object looks like this

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"     

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

2nd array of objects looks like this

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" 

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

And my third object looks like this.

Array[2]

0 : Object
    name:"Blah"     
    fcp:"erol"
1 : Object
    name:"Blah2"        
    fcp:"tpep"

现在,我想基于 ref 价格求和。第一个对象和第二个对象具有共同的参考A和B。因此最终对象看起来像

Now i want to sum the price based on ref. 1st object and 2nd object has ref A and B common. So that the final object looks like

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"  


推荐答案

您可以使用 reduce 函数进行分组

You can use reduce function for groupping

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);

这篇关于合并多个对象数组并求和重复值javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆