You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在JavaScript中按id合并字典列表,将data1合并为数组

按ID归集字典列表中data1值的实现方案

输入示例

[
        {
            "id": "abc",
            "data1": 3,
            "data2": "test1"
        },
        {
            "id": "abc",
            "data1": 4,
            "data2": "test1"
        },
        {
            "id": "xyz",
            "data1": 2,
            "data2": "test2"
        }
]

期望输出

[
        {
            "id": "abc",
            "data1": [3,4],
            "data2": "test1"
        },
        {
            "id": "xyz",
            "data1": [2],
            "data2": "test2"
        }
]

实现方法

方法一:临时字典映射(高效直观)

通过id作为键构建临时字典,快速定位已有条目,避免重复遍历,大数据量场景下性能更优:

input_list = [
    {"id": "abc", "data1": 3, "data2": "test1"},
    {"id": "abc", "data1": 4, "data2": "test1"},
    {"id": "xyz", "data1": 2, "data2": "test2"}
]

temp_map = {}
for item in input_list:
    item_id = item["id"]
    if item_id not in temp_map:
        # 首次遇到该ID,初始化条目并将data1转为数组
        temp_map[item_id] = {
            "id": item_id,
            "data1": [item["data1"]],
            "data2": item["data2"]
        }
    else:
        # 该ID已存在,追加data1值到数组
        temp_map[item_id]["data1"].append(item["data1"])

# 将字典的值转为最终列表
result = list(temp_map.values())
print(result)

方法二:reduce函数实现(函数式风格)

如果偏好函数式编程,可以用reduce完成,但每次迭代需要遍历累加器查找已有ID,适合小数据量场景:

from functools import reduce

input_list = [
    {"id": "abc", "data1": 3, "data2": "test1"},
    {"id": "abc", "data1": 4, "data2": "test1"},
    {"id": "xyz", "data1": 2, "data2": "test2"}
]

def merge_entries(accumulator, current_item):
    # 查找累加器中是否已有当前ID的条目
    existing_entry = next((entry for entry in accumulator if entry["id"] == current_item["id"]), None)
    if existing_entry:
        existing_entry["data1"].append(current_item["data1"])
    else:
        # 新增条目,将data1转为数组
        accumulator.append({
            "id": current_item["id"],
            "data1": [current_item["data1"]],
            "data2": current_item["data2"]
        })
    return accumulator

result = reduce(merge_entries, input_list, [])
print(result)

注意事项

  • 上述代码默认相同ID的data2值完全一致,如果存在同ID但data2不同的情况,需额外处理(比如保留第一个值、合并所有值等),可根据实际需求调整逻辑。

内容的提问来源于stack exchange,提问作者br0ek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 00:20:24