Home >Web Front-end >JS Tutorial >How to Conditionally Add Members to a JavaScript Object?
Conditionally Adding Members to an Object in JavaScript
Question: How can I dynamically add members to an object, depending on certain conditions, in JavaScript?
Initial Approach:
One straightforward approach is to use an if statement to add the member if the condition is met:
var a = {}; if (someCondition) a.b = 5;
Idiomatic Solution:
To write a more idiomatic and concise code, avoid using undefined as the value for conditional members. Instead, use the conditional ternary operator:
a = { b: (someCondition? 5 : undefined) };
However, this approach still results in the b member being defined with an undefined value if the condition is not met.
ES6 Solution with Logical AND:
For the general case with multiple members, ES6 introduces a clever solution using the spread operator and logical AND short-circuit evaluation:
const a = { ...(someCondition && {b: 5}) }
The logical AND (&&) operator evaluates to false if any of its operands are false. Since undefined is false in JavaScript, if someCondition is false, the {b: 5} object is not included in the spread operator, effectively preventing the b member from being added to the object.
The above is the detailed content of How to Conditionally Add Members to a JavaScript Object?. For more information, please follow other related articles on the PHP Chinese website!