Sometimes, we want to conditionally add a member to a JavaScript object.
In this article, we’ll look at how to conditionally add a member to a JavaScript object.
Spread Operator
We can use the spread operator to spread an object into another object conditionally.
For instance, we can write:
const condition = true
const obj = {
...(condition && {
b: 5
})
}
console.log(obj)
We use the && operator to return the object only when condition is true .
If the object is returned then it’ll be spread into obj .
And so we get:
{b: 5}
as a result.
Instead of using the && operator, we can also use the ternary operator by writing:
const condition = true
const obj = {
...(condition ? {
b: 5
} : {})
}
console.log(obj)
We return an empty object when condition is false instead of null .
Object.assign
Also, we can use the Object.assign method to merge an object into another object.
For instance, we can write:
const condition = true
const obj = Object.assign({}, condition ? {
b: 5
} : null)
console.log(obj)
We have the condition check in the 2nd argument of the Object.assign method.
We return the object only when condition is true .
Otherwise, null is returned.
Since condition is true , we have the same result for obj .
Conclusion
We can add properties to an object conditionally with the spread operator or the Object.assign method.
We can use the ternary operator or && operator to specify what to add given the condition.