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

Objects are the most important data-type and are building blocks for modern JavaScript. They are different from primitive data-types such as String, Number, Boolean, null, etc. But we can make these datatypes as objects by using the new keyword. There are two approaches to conditionally add a member to an object.

Method 1: This method involves checking if the required condition is true and based on that a property is added to the object. 

Example: In this example, if the condition is true then ‘b’ will be added as a member to ‘a’, otherwise not.

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Define the object
var a = {};
  
// Check if the condition
// is satisfied
if (someCondition) {
      
    // Add the required 
    // property to the object 
    a.b = 7;
}

chevron_right


Output:



  • When condition is satisfied:

    {b: 7}
  • When condition is not satisfied:

    {}

This approach can also be used in an idiomatic way, using a ternary operator.

Example: In this example, if the condition is true then ‘b’ will be added as a member to ‘a’, otherwise not.

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

var a = {
    // Use the ternary operator to check
    // if the property should be added
    // to the object
    b: (someCondition? 7 : undefined)
};

chevron_right


Output:

  • When condition is satisfied:

    {b: 7}
  • When condition is not satisfied:

    {b: undefined}

Method 2: This method is used to add several members to an object. The jQuery library function $.extend() is used for this method. This however does not copy undefined properties to the object.

Example:

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

var newObject = $.extend({}, {
  a: conditionA ? 7 : undefined,
  b: conditionB ? 9 : undefined,
    
  // More properties as required
});

chevron_right


Output:

  • When the first condition is satisfied:

    {a: 7}
  • When both conditions are satisfied:

    {a: 7, b: 9}

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.