js数组里的对象相同key合并,其余多个相同key值相加

2024年07月22日 建站教程

let list=[
  {
    "year": 2021,
    "price0": 12,
    "price1": 0,
    "price2": 22
  },
  {
    "year": 2022,
    "price0": 1,
    "price1": 32,
    "price2": 121
  },
  {
    "year": 2021,
    "price0": 0,
    "price1": 0,
    "price2": 0
  },
  {
    "year": 2022,
    "price0": 24195.36,
    "price1": 76262.56,
    "price2": 0
  }
]

合并方法

function someDataMerge(arr, sameKey, mergeKey){
  var result = [];
  var temp = {};
  for (var i in arr) {
  	var key = arr[i][sameKey];
  	if (temp[key]) {
  	  temp[key][sameKey] = temp[key][sameKey];
  	  for(var j=0;j<mergeKey.length; j++){
  	  	temp[key][mergeKey[j]] = temp[key][mergeKey[j]] + arr[i][mergeKey[j]];
  	  }
  	} else {
  	  temp[key] = {};
  	  temp[key][sameKey] = arr[i][sameKey];
  	  for(var j=0;j<mergeKey.length; j++){
  	  	temp[key][mergeKey[j]] = arr[i][mergeKey[j]];
  	  }
  	}
  	//不用合并的值
  }
  for (var k in temp) {
  	result.push(temp[k])
  }
  return result;
}

调用

//哪些值需要合并
var mergeKey = ["price0", "price1", "price2"]

//调用
var results = someDataMerge(list, "year", mergeKey);

//说明
//list数组
//year根key合并
//mergeKey需要合并相加的key

//输出结果
console.log(results)

//0: {year: 2021, price0: 12, price1: 0, price2: 22}
//1: {year: 2022, price0: 24196.36, price1: 76294.56, price2: 121}

本文链接:http://so.lmcjl.com/news/8935/

展开阅读全文