111

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: ''
}
6
  • 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) Commented Feb 20, 2019 at 15:08
  • 27
    Object.fromEntries(['a', 'b', 'c'].map(k => [k, ''])); Commented Nov 14, 2021 at 20:15
  • 2
    The duplicates here make no sense. Commented May 25, 2023 at 18:15
  • 1
    @Liam The duplicate stackoverflow.com/questions/54218671/… seems to ask the same question. Commented May 27, 2023 at 8: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! Commented Jun 27, 2023 at 9:06

5 Answers 5

196

Try with Array.reduce():

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

Sign up to request clarification or add additional context in comments.

5 Comments

whatt does returning (a[b] = '',a) mean? what does the second argument do?
@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
Could somebody add a Typescript version of this?
@cbdeveloper typescript version mycompiler.io/view/AlipcFS
@ShivamSahil a good explanation of how the comma operator works: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
57

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);

3 Comments

Why do simple when you can do complicated...
From an eslint point of view this syntax is less ambiguous than the most voted one, +1.
Your solution is slower then "arr.reduce((ac,a)=>(ac[a]='',ac),{})" because off object is recreated at every iteration
22
const target = {}; ['a','b','c'].forEach(key => target[key] = "");

6 Comments

Why do you use map to iterate over an array ? You could have chosen forEach
Usually Array.prototype.map is used to create a new array and the function passed to map is a pure function.
I don't understand why everybody was trying to complicate everything with reduce when there was such an obvious and simple answer
@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'.
"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
|
16

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);

Comments

12

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)

1 Comment

I think this one have the most readable 'reduce' approach

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.