如何将数组转换为对象(键为数组元素,值为 true)
如何将数组转换为对象(键为数组元素,值为 true)?
在 JavaScript 开发中,我们经常需要将数组转换为特定格式的对象。例如,将以下数组:
["perm-1", "subperm-51", "subperm-52", "subperm-53"]
转换为一个对象,其中每个数组元素作为键,值均为 true
:
{
"perm-1": true,
"subperm-51": true,
"subperm-52": true,
"subperm-53": true
}
本文将介绍 5 种实现方法,并给出最佳实践建议。
方法 1:使用 Object.fromEntries + map
(ES2019+ 推荐)
const array = ["perm-1", "subperm-51", "subperm-52", "subperm-53"];
const result = Object.fromEntries(array.map(item => [item, true]));
- 原理:将数组映射为 [[key, value], …] 格式,再转换为对象。
- 优点:代码简洁,一行完成。
方法 2:使用 reduce
**(兼容性好)**
const result = array.reduce((acc, item) => {
acc[item] = true;
return acc;
}, {});
- 原理:遍历数组,将每个元素作为键添加到累积对象中。
- 优点:兼容旧版浏览器,无需 polyfill。
方法 3:for…of 循环
(传统循环方式)
const result = {};
for (const item of array) {
result[item] = true;
}
- 原理:显式遍历数组,直接操作对象。
- 优点:直观易懂,性能优异。
方法 4:forEach
(函数式风格)
const result = {};
array.forEach(item => (result[item] = true));
- 原理:通过 forEach 遍历数组,副作用修改对象。
- 注意:代码紧凑,但依赖外部变量。
方法 5:Object.assign + 扩展运算符
(不推荐,仅作了解)
const result = Object.assign({}, ...array.map(item => ({ [item]: true })));
- 原理:将数组转换为多个 {key: true} 对象,再合并。
- 缺点:代码可读性差,性能略低。
🏆 推荐方法
- 现代浏览器/Node.js:优先使用 Object.fromEntries(方法 1)。
- 兼容旧环境:选择 reduce(方法 2)或 for…of(方法 3)。
完整示例
const array = ["perm-1", "subperm-51", "subperm-52", "subperm-53"];
const result = Object.fromEntries(array.map(item => [item, true]));
console.log(JSON.stringify(result, null, 2));
// 输出:
// {
// "perm-1": true,
// "subperm-51": true,
// "subperm-52": true,
// "subperm-53": true
// }
兼容性处理
如果需要在 不支持 Object.fromEntries
的环境中使用方法 1,可添加 polyfill:
if (!Object.fromEntries) {
Object.fromEntries = function(entries) {
const obj = {};
entries.forEach(([key, value]) => (obj[key] = value));
return obj;
};
}
总结
方法 | 代码简洁性 | 兼容性 | 可读性 |
---|---|---|---|
Object.fromEntries | ⭐⭐⭐⭐ | 现代 | ⭐⭐⭐⭐ |
reduce | ⭐⭐⭐ | 全 | ⭐⭐⭐ |
for...of | ⭐⭐⭐ | 全 | ⭐⭐⭐⭐ |
根据自己的需求选择最适合的方案!🚀
扩展阅读
解锁数组操作新维度:flatMap 深度解析与实战指南
玩转JavaScript排序黑魔法:Infinity的正确打开方式