Home >Web Front-end >JS Tutorial >How Can I Add Object Members Conditionally in JavaScript Without Undefined Properties?

How Can I Add Object Members Conditionally in JavaScript Without Undefined Properties?

Linda Hamilton
Linda HamiltonOriginal
2024-12-23 10:27:45795browse

How Can I Add Object Members Conditionally in JavaScript Without Undefined Properties?

Adding Object Members Conditionally in JavaScript

In JavaScript, it is common to add members to objects dynamically. However, when these additions need to be conditional, the simplest approach often leads to undefined members.

In the attempt to create an idiomatic code:

a = {
    b: (someCondition? 5 : undefined)
};

the b member is added to the a object regardless of the someCondition result, resulting in its value being undefined if the condition is false.

To resolve this, a more concise solution can be employed using the spread operator (...) and logical AND short circuit evaluation (&&):

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

This code eliminates the need for conditional operators. The spread operator expands the curly braces into the a object, adding the b member if someCondition is true. The logical AND short circuit evaluation ensures that the curly braces are only evaluated if someCondition is true, preventing the addition of an undefined member.

This approach can be easily extended to handle multiple conditional members:

const a = {
   ...(conditionB && {b: 5}),
   ...(conditionC && {c: 5}),
   ...(conditionD && {d: 5}),
   ...(conditionE && {e: 5}),
   ...(conditionF && {f: 5}),
   ...(conditionG && {g: 5}),
}

The above is the detailed content of How Can I Add Object Members Conditionally in JavaScript Without Undefined Properties?. 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