DEV Community

Cover image for How to add properties in object conditionally
Wadie
Wadie

Posted on

How to add properties in object conditionally

How to add properties in object conditionally

When building an object in JavaScript or TypeScript, it's common to add properties conditionally, based on the evaluation of expressions. This is typically done using the spread operator (...) in combination with logical conditions.

const condition = (a, b)  a  b; const obj = {
          a: 1, b: 2,
          ... (false && {c: 3}), 
          ... (true && {d: 4}), 
          ... (condition (1, 2) && {e: 5}),
        }; 
console.log(obj); // output: { a: 1, b: 2, d: 4 }
Enter fullscreen mode Exit fullscreen mode

Explanation

  • false && {c: 3}: This evaluates to false, meaning the {c: 3} object is not spread into obj.

  • true && {d: 4}: Since the condition is true, {d: 4} is spread into obj.

  • condition(1, 2) && {e: 5}: The condition function evaluates whether a > b. Since 1 > 2 is false, the object {e: 5} is not spread.

This technique is a powerful way to keep your object definition clean and concise while adding properties dynamically based on various conditions.

Output

The final object looks like this:
{ a: 1, b: 2, d: 4 }

Top comments (0)