javascript - 有没有办法在一行中从数组值设置对象键
问题描述
说我有一个这样的数组:
const myArray = ['HP', 'QP', 'PS'];
我想要一个对象,其键是myArray
的值,例如
{ HP: 0, QP: 0, PS: 0 }
有没有办法在一行中执行以下操作:
const myObj = {};
myArray.forEach(item => myObj[item] = 0);
解决方案
尝试使用reduce
:
const myArray = ['HP', 'QP', 'PS'];
const myObj = myArray.reduce((a, key) => Object.assign(a, { [key]: 0 }), {});
console.log(myObj);
在较新的环境中,您还可以使用Object.fromEntries
:
const myArray = ['HP', 'QP', 'PS'];
const myObj = Object.fromEntries(myArray.map(key => [key, 0]));
console.log(myObj);
推荐阅读
- c# - System.IO.FileLoadException,找不到程序集,程序集版本冲突
- javascript - 如何在更新 asp.net 中的行时更改 GridView 的特定输入字段值
- swift - 这个错误是什么意思:错误:创建传输失败:noSupportedTransportAvailable
- rust - 迭代向量元素的组合并操作元素
- html - 在下创建下拉列表时出错在角度 7
- javascript - 如何从 AJAX responseText 中获取价值
- sql - 从大量表中检索数据的最有效方法 (20-30)
- angular - 如何在页面上播放音频加载或角度 6+ 中的每个设置间隔
- css - Flexbox - 顶部对齐内容
- c++ - Static member function and access operator