How to conditionally add properties to a javascript object literal

If you can use ES6, use the spread properties.

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

Leave a Comment