How to conditionally add a member to an object using JavaScript?


The object is the most important data type of JavaScript. Even everything is an object in JavaScript. For example, Array is an object, and Number, String, and Boolean can also be an object.

Sometimes, developers require to insert properties into the object based on some condition. For example, we have an object of the person, and we only require adding the driving licence property if a person is 18 years old.

Here, we will learn different approaches to adding a member to an object using JavaScript conditionally.

Using the Spread Operator to add a Member to an Object Conditionally

The first approach to add members to an object conditionally is using the spread operator. If the condition evaluates true, we can use the spread operator with the condition and add a property to the object.

Syntax

Users can follow the syntax below to use the spread operator to add the object properties conditionally into the object.

let obj = {
   ...(condition ? { prop: 'value' } : {})
}

In the above syntax, if the condition is true, it will add a property with a value to the ‘obj’ object. Otherwise, it will add a null object.

Example 1

In the example below, we have created the demo object containing the three different properties and values. After that, we defined the ‘addProp4’ and ‘addProp5’ boolean variables.

We use the spread operator and add the ‘prop4’ and ‘prop5’ properties to the object based on the value of the ‘addProp4’ and ‘addProp5’ variables. In the output, users can observe that the ‘prop4’ property is added to the object but not the ‘prop5’ property.

<html>
<body>
   <h3> Using the <i> spread operator </i> to add members in object conditionally </h3>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      let demo = {
         prop1: 'value1',
         prop2: 'value2',
         prop3: 'value3'
      }
      output.innerHTML = "Demo object before adding the prop4 and prop5 properties conditionally is " + JSON.stringify(demo) + "<br>";
      let addProp4 = true;
      demo = {
         ...demo,
         ...(addProp4 ? { prop4: 'value4' } : {})
      }
      let addProp5 = false;
      demo = {
         ...demo,
         ...(addProp5 ? { prop5: 'value5' } : {})
      }
      output.innerHTML += "Demo object after adding the prop4 and prop5 properties conditionally is " + JSON.stringify(demo);
   </script>
</body>
</html>

Using the Object.assign() Method

The Object.assign() method is used to add properties to the existing or newly created objects. Furthermore, we can add a property to the object based on certain conditions.

Syntax

Users can follow the syntax below to use the Object.assign() method to add members to the object based on a certain condition.

Object.assign(obj, condition ? { prop4: "value4" } : { })

In the above syntax, ‘obj’ is an initial object to add some properties. The second parameter contains the condition and properties to add based on the condition’s value.

Example 2

The ‘initialOBJ’ object contains some properties and values in the example below. After that, we used the Object.assign() method to add properties to the initialOBJ object based on the condition.

In the example below, the ’10 == 20’ condition always evaluates false. So, it adds the ‘prop5’ property to the object rather than adding the ‘prop4’ property.

<html>
<body>
   <h3> Using the <i> Object.assign() method </i> to add members in object conditionally </h3>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      let initialOBJ = {
         prop1: "value1",
         prop2: "value2",
         prop3: "value3"
      };
      let obj = Object.assign(initialOBJ, 10 == 20 ? { prop4: "value4" } : { prop5: "value5" });
      output.innerHTML += "The object after adding the prop4 and prop5 properties conditionally is " + JSON.stringify(obj);
   </script>
</body>
</html>

Using the Extend() Method of JQuery

As the name suggests, the extend() method allows us to extend the object in JQuery.While inserting the properties into the object, we can assign values based on certain conditions.

Syntax

Users can follow the syntax below to use the extend() method of JQuery.

let updatedOBJ = $.extend(initialObj, { prop: condition ? "Yes" : null);

In the above syntax, the initialObj object contains some object properties. In the second parameter, we assign value to the ‘prop’ properties based on the truth value of the condition.

Example 3

In the example below, the ‘city’ object contains the properties and values related to the city. We update the object using the extend() method and assign the value to the ‘clean’ and ‘trafficFree’ properties based on the given condition.

<html>
<head>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
</head>
<body>
   <h3> Using the <i> extend() method of JQuery </i> to add members in object conditionally </h3>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      let city = {
         name: "Bangalore",
         population: 10000000,
         area: 1000
      };
      let isCityClean = true;
      let isTrafficFree = false;
      let updatedOBJ = $.extend(city, { clean: isCityClean ? "Yes" : "No", trafficFree: isTrafficFree ? "Yes" : "No" });
      output.innerHTML += "The object after adding the prop4 and prop5 properties conditionally is " + JSON.stringify(updatedOBJ);
   </script>
</body>
</html>

Use the if Statement

The if statement is the easiest way to add the object property conditionally. If the condition evaluates true, add a property to the object using the dot operator.

Syntax

Users can follow the syntax below to use the if statement to conditionally add properties to the object.

if ( condition ) {
   obj.prop = value;
} 

If the condition becomes true in the above syntax, it will add the ‘prop’ property to the ‘obj’ object.

Example 4

In the example below, the ‘windowOBJ’ object contains various properties related to the window. We have defined the ‘isGlassWindow’ boolean variable and initialized it with the true value.

Here, the value of the ‘isGlassWindow’ variable is true, and it will add the ‘glass’ property with the ‘yes’ value in the ‘windowOBJ’ object.

<html>
<body>
   <h3> Conditionally assigning the <i> values to the object properties </i> to add members in object conditionally </h3>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      let windowOBJ = {
         size: "10 X 10",
         color: "red",
      }
      let isGlassWindow = true;
      if (isGlassWindow) {
         windowOBJ.glass = "yes";
      } else {
         windowOBJ.glass = "no";
      }
      output.innerHTML += "The object after adding the prop4 and prop5 properties conditionally is " + JSON.stringify(windowOBJ);
   </script>
</body>
</html>

Users learned four approaches to adding the member to the object based on a certain condition. The first approach is the most efficient approach using the spread operator. The second approach uses the Object.assign() method. The third approach uses the extend() method of JQuery, and the found approach uses the if statement.

Updated on: 20-Apr-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements