I am trying to e 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"
}
I am trying to e 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"
}
Share
Improve this question
edited Apr 2, 2019 at 14:11
Emile Bergeron
17.4k5 gold badges85 silver badges132 bronze badges
asked Apr 2, 2019 at 14:05
a.tokayevaa.tokayeva
772 silver badges13 bronze badges
5
-
1
objectToCreate[prop] = true;
— there's no need to create a capital-B Boolean object. – Pointy Commented Apr 2, 2019 at 14:06 - @Pointy tried this way too, same result – a.tokayeva Commented Apr 2, 2019 at 14:08
-
2
Your edited code returns - >
{ arrayValue: true, anotherArrayValue: true, arrayValueAsWell: true}
isn't that what you want ? – Mihai T Commented Apr 2, 2019 at 14:10 -
1
Why are you mixing
var
andlet
? – Emile Bergeron Commented Apr 2, 2019 at 14:12 -
Just to note,
myArrayConverted
will beundefined
.Array.prototype.forEach()
returnsundefined
. – Jordan Stubblefield Commented Apr 2, 2019 at 14:16
4 Answers
Reset to default 5You 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);
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);
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)';
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);