"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to add properties in object conditionally

How to add properties in object conditionally

Published on 2024-11-03
Browse:734

How to add properties in object conditionally

How to add properties in object conditionally

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 }

Explanation

  • 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.

Output

The final object looks like this:
{ a: 1, b: 2, d: 4 }

Release Statement This article is reproduced at: https://dev.to/wadie/how-to-add-properties-in-object-conditionally-11n6?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

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