Reputation: 2155
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
Reputation: 1110
const myArray = ["checkbox1Value", "checkbox4Value"];
let obj = {};
myArray.forEach(val => {
obj[val] = true;
})
console.log(obj);
Upvotes: 3
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
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
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
Reputation: 9263
You could map it to an object like so
const obj = {}
["checkbox1Value", "checkbox4Value"].forEach(val => {
obj[val] = true
}
Upvotes: 1