How to conditionally add a member to a JavaScript object?

This article describes how to add a member to a JavaScript object only if a condition is met. We demostrate it in pure JS and also in JQuery.

Pure JavaScript version

In pure javascript, the most compact solution I could come up with is this:

var myObject = {};

if(true) myObject.member1 = 10;
if(false) myObject.member2 = 20;
if(true) myObject.member3 = 30;

In this example only the first and third member will be added. It is quite okay, but looks a bit verbose, especially because all of the assignments are separate statements, and you have to write down the name of the object multiple times. It would be good to have a solution that can handle conditional adding when declaring the object. Let’s look at jQuery…

jQuery version

As you might expect, in jQuery it is a bit more compact. Let’s see the solution:

var myObject = $.extend({}, {
    member1: true  ? 10 : undefined,
    member2: false ? 20 : undefined,
    member3: true  ? 30 : undefined,

As you can see, it looks better, and you can assign the members when you are creating the object. However, you have to write undefined in all places, but even considering that, it is a more compact solution.

This code uses the extend function that can add the members of one JavaScript object to another JavaScript object. As you can see we set all the attributes of the second object, but only the ones that have a value that is not undefined will be set.