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
Release: 2024-12-23 10:27:45
Original
794 people have browsed it

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)
};
Copy after login

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})
}
Copy after login

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}),
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template