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

JavaScript如何将数组元素转为对象键并默认赋值为空字符串

JavaScript数组转目标结构对象实现方案

以下是两种常用的稳定实现方式:

方案1:使用Object.fromEntries(ES2019+支持,写法简洁)

该方法适合支持ES2019及以上规范的运行环境,代码逻辑清晰易读:

const ListValues = ["id", "name", "description"];
const initialValues = Object.fromEntries(ListValues.map(key => [key, ""]));

方案2:使用Array.prototype.reduce(兼容性更好,ES5即可支持)

如果需要兼容低版本运行环境,可以选择reduce方案,兼容性更强:

const ListValues = ["id", "name", "description"];
const initialValues = ListValues.reduce((result, currentKey) => {
  result[currentKey] = "";
  return result;
}, {});

两种方案运行后得到的initialValues都和你要求的预期输出完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 00:24:03