Home  >  Article  >  Web Front-end  >  How to add properties in object conditionally

How to add properties in object conditionally

WBOY
WBOYOriginal
2024-09-08 20:35:09451browse

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 }

The above is the detailed content of How to add properties in object conditionally. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn