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.
// Define the object var a = {};
// Check if the condition // is satisfied if (someCondition) {
// Add the required
// property to the object
a.b = 7;
} |
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.
var a = {
// Use the ternary operator to check
// if the property should be added
// to the object
b: (someCondition? 7 : undefined)
}; |
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:
var newObject = $.extend({}, {
a: conditionA ? 7 : undefined,
b: conditionB ? 9 : undefined,
// More properties as required
}); |
Output:
-
When the first condition is satisfied:
{a: 7}
-
When both conditions are satisfied:
{a: 7, b: 9}