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!