Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Conditionally change object property with JavaScript?
To conditionally change object properties in JavaScript, you can use the logical AND operator (&&) combined with the spread operator. This approach allows you to merge properties into an object only when a condition is true.
How It Works
The logical AND operator returns the second operand if the first is truthy, or false if the first is falsy. When spreading false into an object, it has no effect, making it perfect for conditional property assignment.
Syntax
let newObject = {
...originalObject,
...condition && { propertyName: value }
};
Example: Conditional Property Update
let marksDetails = { Mark1: 33, Mark2: 89 };
let isBacklog = false;
console.log("Result when backlog is set to false:");
console.log({ ...marksDetails, ...isBacklog === true && { Mark1: 33 }});
isBacklog = true;
console.log("Result when backlog is set to true:");
console.log({ ...marksDetails, ...isBacklog === true && { Mark1: 93 }});
Result when backlog is set to false:
{ Mark1: 33, Mark2: 89 }
Result when backlog is set to true:
{ Mark1: 93, Mark2: 89 }
Multiple Conditional Properties
You can conditionally add multiple properties by chaining the pattern:
let student = { name: "John", age: 20 };
let isPassing = true;
let hasScholarship = false;
let result = {
...student,
...isPassing && { status: "Pass", grade: "A" },
...hasScholarship && { scholarship: 5000 }
};
console.log(result);
{ name: 'John', age: 20, status: 'Pass', grade: 'A' }
Alternative Approaches
| Method | Syntax | Best For |
|---|---|---|
| Logical AND | ...condition && { key: value } |
Simple conditions |
| Ternary Operator | ...condition ? { key: value } : {} |
Complex conditions |
| Object.assign() | Object.assign({}, obj, condition && { key: value }) |
Older browsers |
Conclusion
The logical AND operator with spread syntax provides a clean way to conditionally add properties to objects. This pattern is widely used in modern JavaScript for creating new objects with conditional properties.
