Los Morales
Los Morales

Reputation: 2155

Convert string array into field names using javascript

Was wondering if there was a nice way in javascript, preferably es6, to convert a string array that was a result from a map function into field names in a dynamically created object.

For example, say I get the following result from my map function:

["checkbox1Value", "checkbox4Value"]

I would like to do this with those results:

const answer = {
     //some other fields dynamically created
     checkbox1Value: true,
     checkbox4Value: true 
}

Anyway of doing this via es6?

Upvotes: 0

Views: 639

Answers (5)

Thomas B. Lze
Thomas B. Lze

Reputation: 1110

const myArray = ["checkbox1Value", "checkbox4Value"];

let obj = {};

myArray.forEach(val => {
    obj[val] = true;
})

console.log(obj);

Upvotes: 3

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94339

    let result = ["checkbox1Value", "checkbox4Value"];
    const answer = result.reduce((acc, cur) => {acc[cur] = true; return acc}, {});

    console.log(answer);

.reduce is really just a fancy for loop (an "ES6 way of doing it"). If you are shooting for maximum efficiency, use a regular for loop instead.

Upvotes: 3

Aurel Bílý
Aurel Bílý

Reputation: 7983

Nothing extremely ES6-y about this:

let keys = ["checkbox1Value", "checkbox4Value"];
let obj = {};
for (let key of keys) {
  obj[key] = true;
}
console.log(obj);

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386680

You could use computed property names and map the single objects and assign it to a single object.

var array = ["checkbox1Value", "checkbox4Value"],
    object = Object.assign(...array.map(k => ({ [k]: true })));

console.log(object);

Upvotes: 4

Stretch0
Stretch0

Reputation: 9263

You could map it to an object like so

const obj = {}
["checkbox1Value", "checkbox4Value"].forEach(val => {
    obj[val] = true
}

Upvotes: 1

Related Questions