首页 > 解决方案 > 有没有办法在一行中从数组值设置对象键

问题描述

说我有一个这样的数组:

const myArray = ['HP', 'QP', 'PS'];

我想要一个对象,其键是myArray的值,例如

{ HP: 0, QP: 0, PS: 0 }

有没有办法在一行中执行以下操作:

const myObj = {};
myArray.forEach(item => myObj[item] = 0);

标签: javascriptarraysobject

解决方案


尝试使用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);


推荐阅读