我试图想出循环遍历值数组的方法,将每个值保存为键并为每个键分配一个“true”布尔值。
目标是创建以下对象:
{
"arrayValue" : true,
"anotherArrayValue" : true,
"arrayValueAsWell" : true
}
Run Code Online (Sandbox Code Playgroud)
我在做:
var objectToCreate = {};
let myArray = ["arrayValue", "anotherArrayValue", "arrayValueAsWell"]
let myArrayConverted = myArray.forEach((prop,index) => objectToCreate[prop] = true)
Run Code Online (Sandbox Code Playgroud)
并得到:
{
0 : "arrayValue",
1 : "anotherArrayValue",
2 : "arrayValueAsWell"
}
Run Code Online (Sandbox Code Playgroud)
您可以使用Array.prototype.reduce这样的键创建一个对象:
const myObject = ["arrayValue", "anotherArrayValue", "arrayValueAsWell"]
.reduce((acc, value) => ({ ...acc, [value]: true }), {});
console.log(myObject);
Run Code Online (Sandbox Code Playgroud)