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
Release: 2024-12-14 08:16:11
Original
721 people have browsed it

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

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

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

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!

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