DEV Community


Posted on

How to Conditionally Add Property to the Object in JavaScript

In JavaScript, there are several ways to conditionally add elements to an object based on certain conditions. This flexibility allows us to dynamically modify objects as needed. In this post, i will talk about two different ways to accomplish this task. Let's dive in!

Method 1: Spread Operator and Logical AND Operator
This method allows you to add items to the object depending on the condition. If the condition is not true, no new item is added to the object.


let object = {
   ...(condition here) && {prop: propvalue},
Enter fullscreen mode Exit fullscreen mode

Method 2: Ternary Operator
This method only allows you to add the value of the key conditionally, the element is defined to the object in both conditions.


let object = {};

object.newKey = condition ? value : defaultValue;
Enter fullscreen mode Exit fullscreen mode

Can be useful:

Top comments (0)