DEV Community

CodErdal
CodErdal

Posted on

3

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

API Trace View

Struggling with slow API calls?

Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay