Convert array to object keys

Javascript

Javascript Problem Overview


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: ''
}

Javascript Solutions


Solution 1 - Javascript

try with Array#Reduce

const arr = ['a','b','c'];
const res = arr.reduce((acc,curr)=> (acc[curr]='',acc),{});
console.log(res)

Solution 2 - Javascript

Solution 3 - Javascript

var target = {}; ['a','b','c'].forEach(key => target[key] = "");

Solution 4 - Javascript

You can use Object.assign property to combine objects created with a map function, please take into account that if 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);

Solution 5 - Javascript

You can use array reduce function & pass an empty object in the accumulator. In this accumulator add 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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMiguel StevensView Question on Stackoverflow
Solution 1 - JavascriptprasanthView Answer on Stackoverflow
Solution 2 - JavascriptMaheer AliView Answer on Stackoverflow
Solution 3 - JavascriptAlexusView Answer on Stackoverflow
Solution 4 - JavascriptKrzysztof KrzeszewskiView Answer on Stackoverflow
Solution 5 - JavascriptbrkView Answer on Stackoverflow