In Javascript, how to conditionally add a member to an object?

I think @InspiredJW did it with ES5, and as @trincot pointed out, using es6 is a better approach. But we can add a bit more sugar, by using the spread operator, and logical AND short circuit evaluation:

const a = {
   ...(someCondition && {b: 5})
}

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:

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).


const obj = {
   ...(condition) && {someprop: propvalue},
   ...otherprops
}

Live Demo:

const obj = {
  ...(true) && {someprop: 42},
  ...(false) && {nonprop: "foo"},
  ...({}) && {tricky: "hello"},
}

console.log(obj);

I suggest the following:

const a = {
   ...(someCondition? {b: 5}: {})
}

Tags:

Javascript