Reputation: 77
I am trying to come up with the way to loop through an array of values, save each value as a key and assign a 'true' boolean value for each key.
The goal is to create the following object:
{
"arrayValue" : true,
"anotherArrayValue" : true,
"arrayValueAsWell" : true
}
I am doing:
var objectToCreate = {};
let myArray = ["arrayValue", "anotherArrayValue", "arrayValueAsWell"]
let myArrayConverted = myArray.forEach((prop,index) => objectToCreate[prop] = true)
and getting:
{
0 : "arrayValue",
1 : "anotherArrayValue",
2 : "arrayValueAsWell"
}
Upvotes: 0
Views: 2830
Reputation: 386550
You could map object and assign them all to one object with Object.assign
var array = ["arrayValue", "anotherArrayValue", "arrayValueAsWell"],
object = Object.assign(...array.map(k => ({ [k]: true })));
console.log(object);
Upvotes: 0
Reputation: 68933
The return value of forEach()
is undefined
. You also should assign the value to the object key with assignment (=
) operator:
var objectToCreate = {};
let myArray = ["arrayValue", "anotherArrayValue", "arrayValueAsWell"];
myArray.forEach(prop => objectToCreate[prop] = true);
console.log(objectToCreate);
Upvotes: 3
Reputation: 523
You could iterate the array and assign to the objectToCreate
, like this:
var objectToCreate = {};
let myArray = ["arrayValue", "anotherArrayValue", "arrayValueAsWell"];
myArray.forEach(key => objectToCreate[key] = true)';
Upvotes: 0
Reputation: 619
You can use Array.prototype.reduce
to create an object with the keys like this:
const myObject = ["arrayValue", "anotherArrayValue", "arrayValueAsWell"]
.reduce((acc, value) => ({ ...acc, [value]: true }), {});
console.log(myObject);
Upvotes: 5