Conditionally adding properties to an object in js/tsx

Today I had an issue where I wanted to create an object, and add properties based on certain conditions. In something like VB.net I would use an expando object, but I was working in Typescript and suddenly thought, how the hell do I do that?

So, it took some playing around, but this was the solution.

const myObject = {
  property1: 'value1',
  property2: 'value2',
  ...(booleanCondition ? { property3: 'value3' } : {}),
};

Seems kind of obvious when looking at it. Of course, I was working in Typescript, so normally myObject would be typed, but as I was adding random properties I didn’t type the object.

My object was a little more complex than the above, as I had an optional list within the object, so had to do something slightly different.

const myObject = {
  property1: 'value1',
  ...(booleanCondition ? 
    [
      {
        property2: 'value2',
      }
      {
        property2: 'anotherValue',
      }
    : []
  }

Facebook Comments

Leave a Reply

Your email address will not be published. Required fields are marked *