Home > Software design >  How to assign the same value to different properties in a JS object?
How to assign the same value to different properties in a JS object?

Time:06-18

Is there a way to do so? Something like:

const myObject = { firstProp = secondProp: 1 }

Which would be equal to:

const myObject = { firstProp: 1, secondProp: 1 }

Thanks!

CodePudding user response:

No, there's no way to do that. In an object literal, every property has its own independent expression.

As alternatives to repeating the value, you can use an assignment statement

const myObject = {};
myObect.firstProp = myObject.secondProp = 1;

or a simple variable

const value = 1;
const myObject = { firstProp: value, secondProp: value };

or build the object programmatically

const myObject = Object.fromEntries(["first", "second"].map(key => [key, 1]));
  • Related