How to conditionally add properties to a javascript object literal

javascript, object

Solution

You've pretty much shown a use case for a constructor function instead of using an object literal:

function CustomObject(includeB) {
    this.a = 1;
    if (includeB) {
        this.b = 2;
    }
}

//has `a` only
var obj1 = new CustomObject(false);

//has `a` and `b`
var obj2 = new CustomObject(true);

After re-reading your question it appears that you've got limited access in modifying the function. If I'm understanding your question correctly you can only change a limited portion of the script:

function create(includeB) {
    // modifications may be done here

    // the rest may not change
    return {
        a : 1
    }
}

var obj = create(false);
// obj must have property 'a' ONLY

var obj = create(true);
// obj must have properties 'a' and 'b'

If that's the case, then you could simply skip the later part of the function:

function create(includeB) {
    if (includeB) {
        return {
            a: 1,
            b: 2
        };
    }
    return {
        a: 1
    };
}

Problem

I am trying to do the following to satisfy the requirements of a code builder (Sencha Cmd to be specific). This is the essence I what I need to do. The critical factor is that the function body MUST end with a return of an object literal. I cant return a variable due to restrictions in the builder. So, how to add a property 'b' at the point of the pseudo code below if the parameter 'includeB' is true, but NOT add a property AT ALL if it is false. ie b==undefined or b==null is not allowed. Perhaps it is not possible. ``` function create(includeB) { // Can have code here but the final thing MUST be a return of the literal. // ... return { a : 1 // pseudo code: // if (includeB==true) then create a property called b // and assign a value of 2 to it. // Must be done right here within this object literal } } var obj = create(false); // obj must have property 'a' ONLY var obj = create(true); // obj must have properties 'a' and 'b' ``` Thanks for reading and considering, Murray

Original source

Related problems