conditionally add key to object javascript 1

conditionally add key to object javascript

const a = {
   ...(someCondition && {b: 5})
}

Here is what the above code is Doing:
1. The … operator is used to spread the value of the expression to the right of it into the object literal on the left.
2. The expression to the right of the … operator is a conditional expression.
3. The conditional expression evaluates to either an object literal or undefined.
4. If the conditional expression evaluates to an object literal, the object literal is spread into the object literal on the left.
5. If the conditional expression evaluates to undefined, nothing is spread into the object literal on the left.

Similar Posts