如果多个键是相同的JS,则在对象中求和值 [英] sum values in object if multiple keys are the same JS

查看:250
本文介绍了如果多个键是相同的JS,则在对象中求和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有5个对象:

{ row: aa, col: 1, value: 1 }
{ row: bb, col: 2, value: 1 }
{ row: bb, col: 3, value: 1 }
{ row: aa, col: 1, value: 1 }
{ row: aa, col: 2, value: 1 }

我想总结值 col 相同,因此输出应为:

i want to sum values if row and col are the same, so the output should be:

{ row: aa, col: 1, value: 2 }
{ row: bb, col: 2, value: 1 }
{ row: bb, col: 3, value: 1 }
{ row: aa, col: 2, value: 1 }

感谢您的帮助!

试过这个:
Sum javascript object property一个对象数组中具有相同对象propertyB的值

推荐答案

您可以使用 reduce()和一个存储密钥的对象来执行此操作。

You can do this with reduce() and one object to store keys.

var data = [
  { row: 'aa', col: 1, value: 1 },
  { row: 'bb', col: 2, value: 1 },
  { row: 'bb', col: 3, value: 1 },
  { row: 'aa', col: 1, value: 1 },
  { row: 'aa', col: 2, value: 1 }
]

var o = {}
var result = data.reduce(function(r, e) {
  var key = e.row + '|' + e.col;
  if (!o[key]) {
    o[key] = e;
    r.push(o[key]);
  } else {
    o[key].value += e.value;
  }
  return r;
}, []);

console.log(result)

这篇关于如果多个键是相同的JS,则在对象中求和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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