0

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"
  }
5
  • 1
    objectToCreate[prop] = true; — there's no need to create a capital-B Boolean object. Commented Apr 2, 2019 at 14:06
  • @Pointy tried this way too, same result Commented Apr 2, 2019 at 14:08
  • 2
    Your edited code returns - > { arrayValue: true, anotherArrayValue: true, arrayValueAsWell: true} isn't that what you want ? Commented Apr 2, 2019 at 14:10
  • 1
    Why are you mixing var and let? Commented Apr 2, 2019 at 14:12
  • Just to note, myArrayConverted will be undefined. Array.prototype.forEach() returns undefined. Commented Apr 2, 2019 at 14:16

4 Answers 4

5

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);
Sign up to request clarification or add additional context in comments.

Comments

3

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);

Comments

0

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)';

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.