How to conditionally add a member to an object using JavaScript?
Last Updated :
19 Jun, 2024
Objects are the most important data types 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.
Below are the approaches to conditionally adding a member to an object which are as follows:
Using If Statment
You can use an if
statement to check a condition and then add a property to the object if the condition is met.
Example: To demonstrate adding a member to an object using if statement in JavaScript.
JavaScript
let obj = {};
let condition = true;
if (condition) {
obj.newProperty = "newValue";
}
console.log(obj);
Output{ newProperty: 'newValue' }
Using Logical AND (&&
)
The logical AND (&&
) operator can be used to conditionally execute code. If the condition is true, the right-hand side expression is executed.
Example: To demonstrate adding a member to an object using logical and (&&) in JavaScript.
JavaScript
let obj = {};
let condition = true;
condition && (obj.newProperty = "newValue");
console.log(obj);
Output{ newProperty: 'newValue' }
Using Spread Operator with Conditional Assignment
You can use the spread operator in combination with conditional assignment to create a new object that conditionally includes a property.
Example: To demonstrate adding a member to an object using spread operator with conditional assignment in JavaScript.
JavaScript
let condition = true;
let obj = {
...(condition && { newProperty: "newValue" })
};
console.log(obj);
Output{ newProperty: 'newValue' }
Using Object assign
Method
Object.assign
method
can be used to add properties to an object conditionally.
Example: To demonstrate adding a member to an object using object assign method in JavaScript.
JavaScript
let obj = {};
let condition = true;
Object.assign(obj, condition ? { newProperty: "newValue" } : {});
console.log(obj);
Output{ newProperty: 'newValue' }
Using $.extend() method in JQuery.
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: To demonstrate adding a member to an object using $.extend method in JQuery.
JavaScript
let 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}