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

How Can I Efficiently Add Object Members Conditionally in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-14 08:16:11770browse

How Can I Efficiently Add Object Members Conditionally in JavaScript?

Conditional Object Member Addition in JavaScript

Programmers often need to create objects with members added conditionally. The straightforward approach is straightforward:

var a = {};
if (someCondition)
    a.b = 5;

However, this method creates an undefined value for the member if the condition is false.

To achieve a more idiomatic solution, some developers attempt:

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

However, this method still results in an undefined value for the member.

This article explores a more comprehensive solution that handles multiple members and conditions:

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

This solution leverages the spread operator and logical AND short circuit evaluation to add members conditionally while ensuring that undefined members are omitted.

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