What's the best way to convert an array, to an object with those array values as keys, empty strings serve as the values of the new object.
['a','b','c']
to:
{
a: '',
b: '',
c: ''
}
What's the best way to convert an array, to an object with those array values as keys, empty strings serve as the values of the new object.
['a','b','c']
to:
{
a: '',
b: '',
c: ''
}
Try with Array.reduce():
const arr = ['a','b','c'];
const res = arr.reduce((acc,curr)=> (acc[curr]='',acc),{});
console.log(res)
You can use Array.prototype.reduce()
and Computed property names
let arr = ['a','b','c'];
let obj = arr.reduce((ac,a) => ({...ac,[a]:''}),{});
console.log(obj);
const target = {}; ['a','b','c'].forEach(key => target[key] = "");
You can use the Object.assign property to combine objects created with a map function. Please take into account that, if the values of array elements are not unique, the latter ones will overwrite previous ones.
const array = Object.assign({},...["a","b","c"].map(key => ({[key]: ""})));
console.log(array);
You can use the array reduce function and pass an empty object in the accumulator. In this accumulator, add a key which is denoted by curr
.
let k = ['a', 'b', 'c']
let obj = k.reduce(function(acc, curr) {
acc[curr] = '';
return acc;
}, {});
console.log(obj)
Another option is to use for..of
loop
let k = ['a', 'b', 'c'];
const obj = {};
for (let keys of k) {
obj[keys] = '';
}
console.log(obj)