DEV Community

CodErdal
CodErdal

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.

Example:

let object = {
   ...(condition here) && {prop: propvalue},
   ...otherprops
}
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.

Example:

let object = {};

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

Can be useful:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator

Top comments (0)