2

What is the concisest way to create an object from a list of keys, all set to the same value. For example,

const keys = [1, 2, 3, 4]
const value = 0

What is the tersest way to attain the object

{
  “1”: 0,
  “2”: 0,
  “3”: 0,
  “4”: 0
}
1252748
  • 14,597
  • 32
  • 109
  • 229
  • Does this answer your question? [Create object from array](https://stackoverflow.com/questions/42974735/create-object-from-array) – Tschallacka Jun 16 '20 at 11:09

3 Answers3

6

You can use Object.fromEntries

const keys = [1, 2, 3, 4]
const value = 0

const result = Object.fromEntries(keys.map(k => [k, value]))

console.log(result)
Teneff
  • 30,564
  • 13
  • 72
  • 103
  • Maybe make it clearer in an explanation or something that you're presenting two possible methods and what the advantages/disadvantages of each are. – Tschallacka Jun 16 '20 at 11:08
  • 1
    Beware the [reduce-spread](https://www.richsnapp.com/article/2019/06-09-reduce-spread-anti-pattern) antipattern. – Moritz Roessler Jun 16 '20 at 11:29
5

Should probably be something among:

const keys = [1, 2, 3 ,4];
const value = 0;

console.log(
  keys.reduce((acc, key) => (acc[key] = value, acc), {})
);
Tschallacka
  • 27,901
  • 14
  • 88
  • 133
ZER0
  • 24,846
  • 5
  • 51
  • 54
3

The simplest way I can think of would be to use .reduce();

const keys = [1, 2, 3, 4]
const value = 0

const obj = keys.reduce((carry, item) => {
    carry[item] = value;
    return carry;
}, {});

console.log(obj);
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50