简体   繁体   English

如何有条件地创建具有属性的 JavaScript 对象

[英]How to create JavaScript object with properties conditionally

I am creating an object as following in my Angular Controller.我正在我的 Angular 控制器中创建一个对象,如下所示。 However, I need to make Password and Confirm Password properties conditionally.但是,我需要有条件地设置PasswordConfirm Password属性。

I am currently doing it in an if/else statement.我目前正在if/else语句中执行此操作。 If the condition is true execute the following code else execute the same code without password and confirm_password properties.如果条件为真,则执行以下代码,否则执行相同的代码,无需password和确认confirm_password属性。

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.创建没有所需属性的$scope.newStudentForm then added the on condition然后添加了 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"
    };
}

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 :我会按照Satpal 展示的方式来做,但如果你真的想这样做,可以在对象初始化程序中这样做,但这有点复杂:你使用 spread 来展开undefined或带有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; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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