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 }

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay