When building an object in JavaScript or TypeScript, it's common to add properties conditionally, based on the evaluation of expressions. This is typically done using the spread operator (...) in combination with logical conditions.
const condition = (a, b) → a › b; const obj = { a: 1, b: 2, ... (false && {c: 3}), ... (true && {d: 4}), ... (condition (1, 2) && {e: 5}), }; console.log(obj); // output: { a: 1, b: 2, d: 4 }
false && {c: 3}: This evaluates to false, meaning the {c: 3} object is not spread into obj.
true && {d: 4}: Since the condition is true, {d: 4} is spread into obj.
condition(1, 2) && {e: 5}: The condition function evaluates whether a > b. Since 1 > 2 is false, the object {e: 5} is not spread.
This technique is a powerful way to keep your object definition clean and concise while adding properties dynamically based on various conditions.
The final object looks like this:
{ a: 1, b: 2, d: 4 }
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3