0

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
  • 13,412
  • 30
  • 97
  • 213
  • 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

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
  • 26,440
  • 12
  • 87
  • 129
ZER0
  • 23,634
  • 5
  • 48
  • 53
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
  • 23,635
  • 4
  • 32
  • 50
3

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
  • 26,872
  • 8
  • 62
  • 92
  • 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