How to create JavaScript object with properties conditionally

Issue

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

Create $scope.newStudentForm without the required properties. then added the on condition

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

Answered By – Satpal

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.