Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the same value on multiple keys

Tags:

javascript

How is it possible to set the same value on multiple keys? For example I have the following object:

const obj = {
   a: 5,
   b: 5,
   c: 5,
   d: 6
}

Is there any easy way for example lets say I have array of [a, b, c] (keys) and to spread them in object and set them as keys with same value. Point is to look more classy for example:

const keys =[a, b, c]
const obj = {
  [...keys]: 5
}

I know this would throw error but looking for some shorthand to achieve this

like image 240
Andon Mitev Avatar asked Apr 15 '26 06:04

Andon Mitev


2 Answers

Take the array of keys and map each to an entry of the key and the 5 value:

const keys = ['a', 'b', 'c'];
const obj = {
  ...Object.fromEntries(
    keys.map(key => [key, 5])
  ),
  d: 6
};

console.log(obj);
like image 200
CertainPerformance Avatar answered Apr 17 '26 18:04

CertainPerformance


Something like this works:

const obj = {};
const value = 5;
['a', 'b', 'c'].forEach(key => obj[key] = value);
like image 39
Andreas Dolk Avatar answered Apr 17 '26 19:04

Andreas Dolk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!