Home > Net >  From array to object (with values) - JS
From array to object (with values) - JS

Time:08-05

I would like to turn an array to an object, and to assign "true" to each value, in JS.

From

['lastName', 'firstName', 'email']

to

{lastName: true, firstName: true, email: true}

Thanks for your help

CodePudding user response:

you can do this like that

const array = ['lastName', 'firstName', 'email']
const object = {}
array.forEach((e) => object[e] = true)

CodePudding user response:

Iterate the array and assign true to the values, using them as keys:

let myObject = {};
for (var i = 0; i < myArray.length;   i) {
    let key = myArray[i];
    myObject[key] = true;
}
return myObject;

CodePudding user response:

You can use the reduce() properties Read Here, ex:

const a = ['lastName', 'firstName', 'email']

const b = a.reduce((prev, current) => ({ ...prev, [current]: true}), {}) 

console.log(b)

CodePudding user response:

Seems a good case for Object.fromEntries:

const keys = ['lastName', 'firstName', 'email'];
const result = Object.fromEntries(keys.map(key => [key, true]));

console.log(result);

CodePudding user response:

const obj = {}
const arr = ['lastName', 'firstName', 'email']
    
arr.forEach(function(el){
    obj[el] = true
})
  • Related