javascript - Javascript - 总计并删除对象数组中的重复行
问题描述
我有一组包含一些信息的对象。颜色和大小相同的线,我想求和并删除重复的线,即对于每个颜色和大小相等的,我只想得到一条线。
我的对象数组
data = [
{
tam: 'S',
color: 'blue',
total: 5
},
{
tam: 'S',
color: 'blue',
total: 10
},
{
tam: 'S',
color: 'blue',
total: 20
},
{
tam: 'M',
color: 'blue',
total: 5
},
{
tam: 'L',
color: 'blue',
total: 5
}
];
所需的输出
data = [
{
tam: 'S',
color: 'blue',
total: 35
},
{
tam: 'M',
color: 'blue',
total: 5
},
{
tam: 'L',
color: 'blue',
total: 5
}
];
解决方案
您可以使用reduce
函数来汇总具有相同tam
属性的元素。然后是一个map
创建对象数组的结果:
data = [
{
tam: 'S',
color: 'blue',
total: 5
},
{
tam: 'S',
color: 'blue',
total: 10
},
{
tam: 'S',
color: 'blue',
total: 20
},
{
tam: 'M',
color: 'blue',
total: 5
},
{
tam: 'L',
color: 'blue',
total: 5
}
];
var result = data.reduce(function(acc, x) {
var id = acc[x.tam]
if (id) {
id.tam = x.tam
id.total += x.total
} else {
acc[x.tam] = x
}
return acc
},{});
result = Object.keys(result)
.sort(function(x, y){return +x - +y})
.map(function(k){return result[k]})
console.log(result)
推荐阅读
- flutter - 如何在 Flutter 中处理这个 Text 小部件?
- python - 如何使用纯 Python 而不是 jython 在 nifi 处理器中设置属性?
- javascript - 第一次在带有一堆 if 的 func 中分配值,需要摆脱 if 的
- c++ - WM_CREATE 消息的目的?
- excel - 有没有办法根据不同的字符串作为信号将一张纸中的特定范围复制到另一张纸中的特定范围?
- c++ - 在 C++ 中,对象可以与其基对象共享相同的多态成员吗?
- regex - 为多行字符串中的数字添加偏移量
- unity3d - 缩放后统一获取网格
- vb.net - 碰撞检测编辑图片框的生成位置
- python-3.x - 如何在列表中拆分字符串?