简体   繁体   中英

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"
},

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"
    };
}

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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM