'How to create JavaScript object with properties conditionally

I am creating an object as following in my Angular Controller. However, I need to make Password and Confirm Password properties conditionally.

I am currently doing it in an if/else statement. If the condition is true execute the following code else execute the same code without password and confirm_password properties.

I found that it is repetition of code. Is there nicer way I can mention properties conditionally inside the object?

$scope.newStudentForm = {
rules: {
firstname: {
    required: true
},
lastname: {
    required: true
},
email: {
    required: true,
    email: true
},
password: {
    required: true,
    minlength: 6
},
confirm_password: {
    required: true,
    minlength: 6,
    equalTo: "#password"
},
student_role: "required"
},


Solution 1:[1]

I would do it the way Satpal showed, but if you really want to, it is possible to do this within the object initializer, but it's a bit complex: You use spread to spread out either undefined or an object with isProtected:

$scope.newStudentForm = {
    rules: {
        ...(condition
            ?  {
                password: {
                    required: true,
                    minlength: 6
                },
                confirm_password: {
                    required: true,
                    minlength: 6,
                    equalTo: "#password"
                }
            }
            : undefined
         )
    }
};

Live Example:

function example(condition) {
    return {
        rules: {
            ...(condition
                ?  {
                    password: {
                        required: true,
                        minlength: 6
                    },
                    confirm_password: {
                        required: true,
                        minlength: 6,
                        equalTo: "#password"
                    }
                }
                : undefined
             )
        }
    };
}

console.log("Condition false:");
console.log(example(false));
console.log("Condition true:");
console.log(example(true));
.as-console-wrapper {
    max-height: 100% !important;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 T.J. Crowder