如何有条件地创建JavaScript对象

How to create JavaScript object with properties conditionally

本文关键字:JavaScript 对象 创建 有条件      更新时间:2023-09-26

我正在我的Angular控制器中创建一个对象,如下所示。然而,我需要有条件地制作PasswordConfirm Password属性。

我目前正在if/else语句中做它。如果条件为真,则执行以下代码,否则执行不含passwordconfirm_password属性的相同代码。

我发现这是代码的重复。有没有更好的方法可以在对象中有条件地提及属性?

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

创建没有所需属性的$scope.newStudentForm。然后添加on条件

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

我会按照Satpal展示的方式来做,但是如果您真的想要这样做,可以在对象初始化器中这样做,但这有点复杂:您使用spread来展开undefinedisProtected:

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

生活的例子:

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