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

如何将包含多个单键对象的List转换为合并后的单层Map

单键对象列表合并为单个对象实现方案

核心逻辑:遍历列表中的每一个单键值对对象,将所有键值对合并到同一个空对象中,遇到重复键时后出现的键值会覆盖先出现的键值。

JavaScript 实现

原始输入数据

const sourceList = [
  {welcome_eap: "Welcome to Automation Platform"},
  {eap_version: "V2.1.0"},
  {iot_enable_platform: "IOT Enabled Automation Platform"}
];

转换代码

方案1:使用Object.assign加扩展运算符,一行完成

const targetMap = Object.assign({}, ...sourceList);

方案2:使用reduce方法,兼容性更好

const targetMap = sourceList.reduce((accumulator, current) => {
  return Object.assign(accumulator, current);
}, {});

Python 实现

原始输入数据

source_list = [
    {"welcome_eap": "Welcome to Automation Platform"},
    {"eap_version": "V2.1.0"},
    {"iot_enable_platform": "IOT Enabled Automation Platform"}
]

转换代码

方案1:遍历更新字典,兼容性最好,全Python版本支持

target_map = {}
for item in source_list:
    target_map.update(item)

方案2:字典推导式,一行实现

target_map = {k: v for d in source_list for k, v in d.items()}

方案3:Python 3.9+ 支持的字典合并运算符

target_map = {}
for item in source_list:
    target_map |= item

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 19:45:03