97

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: ''
}
Miguel Stevens
  • 8,631
  • 18
  • 66
  • 125
  • 3
    Can you precise what you mean by "best way"? the more efficient will be a loop, the shortest text will be a functional approach (and all answers will be functional because it's trendy) – Kaddath Feb 20 '19 at 15:08
  • 18
    `Object.fromEntries(['a', 'b', 'c'].map(k => [k, '']));` – luukvhoudt Nov 14 '21 at 20:15
  • 2
    The duplicates here make no sense. – Liam May 25 '23 at 18:15
  • 1
    @Liam The duplicate https://stackoverflow.com/questions/54218671/return-object-with-default-values-from-array-in-javascript seems to ask the same question. – Mark Rotteveel May 27 '23 at 08:30
  • Having closed as duplicate against similar but not the same questions, puts the best answer in the comments of the question... great! Thanks @luukvhoudt for commenting! – TWiStErRob Jun 27 '23 at 09:06
  • Two complainers, but only one vote to reopen. I am voting to reopen. – Rohit Gupta Jun 30 '23 at 05:05

5 Answers5

179

Try with Array.reduce():

const arr = ['a','b','c'];
const res = arr.reduce((acc,curr)=> (acc[curr]='',acc),{});
console.log(res)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
prasanth
  • 22,145
  • 4
  • 29
  • 53
  • 5
    whatt does returning `(a[b] = '',a)` mean? what does the second argument do? – Shivam Sahil Dec 25 '20 at 19:18
  • 3
    @ShivamSahil check now, I have edited the answer. Each time of the loop `current value` inserted into accumulator `acc[curr] = ''` like this. `,acc` is returning the accumulator once loop end. And `,{}` is defined the accumulator is a object – prasanth Dec 26 '20 at 07:14
  • 4
    Could somebody add a Typescript version of this? – cbdeveloper Feb 18 '21 at 16:51
  • 3
    @cbdeveloper typescript version https://www.mycompiler.io/view/AlipcFS – prasanth May 28 '21 at 07:53
  • 4
    @ShivamSahil a good explanation of how the comma operator works: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator – Cezar D. Oct 22 '21 at 19:55
54

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);
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
20
const target = {}; ['a','b','c'].forEach(key => target[key] = "");
Vik
  • 495
  • 1
  • 5
  • 11
Alexus
  • 1,282
  • 1
  • 12
  • 20
  • 2
    Why do you use `map` to iterate over an array ? You could have chosen `forEach` – Serge K. Feb 20 '19 at 15:10
  • forEach would work as well. – Alexus Feb 20 '19 at 15:26
  • 4
    Usually [Array.prototype.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) is used to create a new array and the function passed to map is a pure function. – HMR Feb 20 '19 at 15:32
  • 10
    I don't understand why everybody was trying to complicate everything with reduce when there was such an obvious and simple answer – Tofandel Jun 13 '20 at 23:46
  • 5
    @Tofandel because this is perfect and handy usage of `reduce`... `forEach` requires variable declaration, `reduce` is true one-liner and this is kind of task it was designed for. It's definitely not 'complicated'. – user0103 Jan 28 '21 at 21:27
  • 9
    "True one-liners" are just making code more obscure and harder to understand. Better to add one line and have a code you can understand right away – Tofandel Jan 29 '21 at 10:13
14

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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Krzysztof Krzeszewski
  • 5,912
  • 2
  • 17
  • 30
10

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)
brk
  • 48,835
  • 10
  • 56
  • 78