snippetjavascriptCritical
How to conditionally add a member to an object?
Viewed 0 times
conditionallyobjecthowmemberadd
Problem
I would like to create an object with a member added conditionally.
The simple approach is:
Now, I would like to write a more idiomatic code. I am trying:
But now,
Is there a handy solution?
Update
I seek for a solution that could handle the general case with several members.
The simple approach is:
var a = {};
if (someCondition)
a.b = 5;Now, I would like to write a more idiomatic code. I am trying:
a = {
b: (someCondition? 5 : undefined)
};But now,
b is a member of a whose value is undefined. This is not the desired result.Is there a handy solution?
Update
I seek for a solution that could handle the general case with several members.
a = {
b: (conditionB? 5 : undefined),
c: (conditionC? 5 : undefined),
d: (conditionD? 5 : undefined),
e: (conditionE? 5 : undefined),
f: (conditionF? 5 : undefined),
g: (conditionG? 5 : undefined),
};Solution
In pure Javascript, I cannot think of anything more idiomatic than your first code snippet.
If, however, using the jQuery library is not out of the question, then $.extend() should meet your requirements because, as the documentation says:
Undefined properties are not copied.
Therefore, you can write:
And obtain the results you expect (if
If, however, using the jQuery library is not out of the question, then $.extend() should meet your requirements because, as the documentation says:
Undefined properties are not copied.
Therefore, you can write:
var a = $.extend({}, {
b: conditionB ? 5 : undefined,
c: conditionC ? 5 : undefined,
// and so on...
});And obtain the results you expect (if
conditionB is false, then b will not exist in a).Code Snippets
var a = $.extend({}, {
b: conditionB ? 5 : undefined,
c: conditionC ? 5 : undefined,
// and so on...
});Context
Stack Overflow Q#11704267, score: 142
Revisions (0)
No revisions yet.