Search code examples
javascriptobjectvariablespropertiesassign

Shorthand Method to Create Property in Object only if Variable is defined


Looking for a shorthand method to assign properties to an object ONLY when the assigning variable is defined.

Current Code:

let count = {}, one = 1, two = 2, four = 4;
if (one) count.one = one; 
if (two) count.two = two; 
if (three) count.three = three; 
if (four) count.four = four; 

Result:
count = { one: 1, two: 2, four: 4 }

Normally, I would try this:

let count = { one, two, three, four }

However, it complains when three is undefined...

Is there a better method to shorthand assign only when defined?

What I cannot have:

count = { one: 1, two: 2, three: undefined, four: 4 }


Solution

  • it complains when three is undefined...

    No, it will only complain when the variable three is not declared, not when it has the value undefined. You can easily fix that:

    let one = 1, two = 2, three /* = 3 */, four = 4;
    
    const count = JSON.stringify({one, two, three, four});
    console.log(count);

    If the variable is not used anywhere, you can just omit it, as it never would have any value. If the variable is used (assigned a value somewhere), you need to declare it anyway in strict mode.