Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create object with list of keys

Tags:

javascript

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
}
like image 918
1252748 Avatar asked Oct 19 '25 09:10

1252748


1 Answers

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)
like image 153
Teneff Avatar answered Oct 20 '25 22:10

Teneff