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
}
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
}
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)
Should probably be something among:
const keys = [1, 2, 3 ,4];
const value = 0;
console.log(
keys.reduce((acc, key) => (acc[key] = value, acc), {})
);
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);