4 回答

TA贡献1876条经验 获得超5个赞
在返回的值forEach()是undefined。您还应该使用赋值(=)运算符将值分配给对象键:
var objectToCreate = {};
let myArray = ["arrayValue", "anotherArrayValue", "arrayValueAsWell"];
myArray.forEach(prop => objectToCreate[prop] = true);
console.log(objectToCreate);

TA贡献1951条经验 获得超3个赞
您可以使用Array.prototype.reduce以下键来创建对象:
const myObject = ["arrayValue", "anotherArrayValue", "arrayValueAsWell"]
.reduce((acc, value) => ({ ...acc, [value]: true }), {});
console.log(myObject);

TA贡献1880条经验 获得超4个赞
您可以映射对象并将它们全部分配给一个对象 Object.assign
var array = ["arrayValue", "anotherArrayValue", "arrayValueAsWell"],
object = Object.assign(...array.map(k => ({ [k]: true })));
console.log(object);

TA贡献1802条经验 获得超5个赞
您可以迭代数组并分配给objectToCreate,如下所示:
var objectToCreate = {};
let myArray = ["arrayValue", "anotherArrayValue", "arrayValueAsWell"];
myArray.forEach(key => objectToCreate[key] = true)';
添加回答
举报