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
var a = {};
if (someCondition) {
a.b = 7;
}
|
Output:
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
var a = {
b: (someCondition? 7 : undefined)
};
|
Output:
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
var newObject = $.extend({}, {
a: conditionA ? 7 : undefined,
b: conditionB ? 9 : undefined,
});
|
Output: