按多个属性和求和组对数组项进行分组可以通过以下步骤实现:
以下是一个示例代码(使用Python语言):
def group_by_multiple_properties(arr, group_properties, sum_property):
result = {}
for item in arr:
key = tuple(item[prop] for prop in group_properties)
if key not in result:
result[key] = item.copy()
else:
result[key][sum_property] += item[sum_property]
return result
# 示例用法
data = [
{"name": "A", "category": "X", "value": 10},
{"name": "B", "category": "Y", "value": 20},
{"name": "C", "category": "X", "value": 30},
{"name": "D", "category": "Y", "value": 40},
{"name": "E", "category": "Z", "value": 50},
{"name": "F", "category": "Z", "value": 60}
]
grouped_data = group_by_multiple_properties(data, ["category"], "value")
for key, value in grouped_data.items():
print(key, value)
输出结果为:
('X',) {'name': 'A', 'category': 'X', 'value': 40}
('Y',) {'name': 'B', 'category': 'Y', 'value': 60}
('Z',) {'name': 'E', 'category': 'Z', 'value': 110}
在这个示例中,我们按照属性"category"对数组项进行分组,并对属性"value"进行求和。最终得到了按"category"分组的结果,并计算了每个分组中"value"的总和。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云