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

如何用.map替代.forEach单条语句创建指定键的空字符串值对象

Array.prototype.map 本身的设计就是返回和原数组长度一致的新数组,所以直接用它生成对象肯定达不到预期,有两种常用的简洁实现方式:

方法1:Object.fromEntries + map (最简洁,推荐)

ES2019 引入的 Object.fromEntries 可以直接把 [键, 值] 格式的二维数组转为对象,搭配map使用一行就能搞定:

const keys = ['one', 'two', 'three'];
const result = Object.fromEntries(keys.map(key => [key, '']));
console.log(result); // {one: '', two: '', three: ''}

这个写法兼容性覆盖所有现代浏览器、Node.js 12.0+ 版本,没有特殊兼容要求优先用这个。

方法2:用Array.prototype.reduce聚合

如果需要兼容更低版本的运行环境,可以用reduce做迭代聚合,初始值传入空对象,每次迭代给对象追加键值对即可:

const keys = ['one', 'two', 'three'];
const result = keys.reduce((acc, cur) => {
  acc[cur] = '';
  return acc;
}, {});
// 也可以简写为一行:
// const result = keys.reduce((acc, cur) => (acc[cur] = '', acc), {});
console.log(result); // {one: '', two: '', three: ''}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 11:48:02