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

如何使用扩展运算符从map函数返回键值对合并JavaScript对象

问题:合并对象与数组为单个对象的正确写法

你有如下对象和数组:

const first = { 
  'key1': 'some date',
  'key2': 'some date'
}

const second = ['key3', 'key4']

你希望通过扩展语法将二者合并为一个对象,为数组中的每个元素创建新的键值对并加入合并结果。但当前使用map函数返回的是单个对象,导致最终结果不符合预期,需要修改代码。

当前代码

const combined = {
  ...first,
  ...second.map(key => ({ [key]: new Date() })) // 期望返回键值对而非对象
}

当前错误结果

{
  '0': { key3: 'some date' },
  '1': { key4: 'some date' },
  key1: 'some date',
  key2: 'some date'
}

期望结果

{
  key1: 'some date',
  key2: 'some date',
  key3: 'some date',
  key4: 'some date'
}

解决方案

问题根源在于map返回的是对象数组,扩展数组时会将数组索引作为键、数组元素(单个对象)作为值存入结果。需要先把数组转换成单个目标对象,再进行合并。

方法1:使用Object.fromEntries

const combined = {
  ...first,
  ...Object.fromEntries(second.map(key => [key, new Date()]))
}
  • second.map(key => [key, new Date()])会生成键值对数组:[['key3', new Date()], ['key4', new Date()]]
  • Object.fromEntries将该数组转换为对象:{key3: new Date(), key4: new Date()}
  • 最后通过扩展语法与first合并,得到期望结果。

方法2:使用reduce

const combined = {
  ...first,
  ...second.reduce((acc, key) => {
    acc[key] = new Date();
    return acc;
  }, {})
}
  • reduce遍历数组,将每个键值对添加到初始空对象{}中,最终生成包含数组元素对应键值对的对象
  • 再通过扩展语法与first合并。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 10:00:12