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

JavaScript中如何将数组转换为元素为键、值为true的键值对对象

注意事项

你给出的原始数组示例中的颜色值如果是字符串类型,需要用引号包裹,否则会被识别为未定义变量,正确的数组定义如下:

let colors = ['red', 'blue', 'black', 'yellow', 'orange']

实现方案

方法1:使用 Object.fromEntries(ES2019+ 支持)

写法最简洁直观,先将数组元素映射为[键, 值]格式的二维数组,再直接转换为目标对象:

const colorChecklist = Object.fromEntries(
  colors.map(color => [color, true])
)

方法2:使用 Array.reduce(ES5+ 支持,兼容性更好)

通过累加器遍历数组生成目标对象,适合需要兼容低版本运行环境的场景:

const colorChecklist = colors.reduce((accumulator, currentColor) => {
  accumulator[currentColor] = true
  return accumulator
}, {})
// 简写版本:const colorChecklist = colors.reduce((acc, cur) => (acc[cur] = true, acc), {})

方法3:基础循环写法

全版本JS环境兼容,逻辑最易理解:

const colorChecklist = {}
// 普通for循环写法
for (let i = 0; i < colors.length; i++) {
  colorChecklist[colors[i]] = true
}

// 或for of循环写法(ES6+支持)
// for (const color of colors) {
//   colorChecklist[color] = true
// }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:57:01