0

I want to convert this:

let arr = ['a', 'b', 'c'];

To this:

let obj = { a: null, b: null, c: null };

Thank you :)

Phil
  • 157,677
  • 23
  • 242
  • 245
  • What have you tried? I suggest you give [`Array.prototype.reduce()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) a try, eg `arr.reduce((obj, key) => ({...obj, [key]: null}), {})` – Phil Aug 11 '20 at 02:21

2 Answers2

2

console.log(
    Object.fromEntries(['a', 'b', 'c'].map(x => ([x, null])))
);
GirkovArpa
  • 4,427
  • 4
  • 14
  • 43
  • 1
    Instead of spoon-feeding code to the asker, please consider *explaining* how the code you've answered will help to solve the asker's question. – Edric Aug 11 '20 at 03:15
1

You could use Array#map and object entries to get the desired results you are after.

Demo:

let arr = ['a', 'b', 'c'];

let conv = Object.fromEntries(arr.map(y => ([y, null])))

console.log(conv)
Always Helping
  • 14,316
  • 4
  • 13
  • 29