如何有条件地创建JavaScript对象
How to create JavaScript object with properties conditionally
我正在我的Angular控制器中创建一个对象,如下所示。然而,我需要有条件地制作Password
和Confirm Password
属性。
我目前正在if/else
语句中做它。如果条件为真,则执行以下代码,否则执行不含password
和confirm_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来展开undefined
或isProtected
:
$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;
}
相关文章:
- Chrome开发工具(如何知道我在调用哪个javascript对象)
- 循环遍历以数组为值的Javascript对象
- 从ajax请求中获取javascript对象
- 如何从对象的原型方法访问JavaScript对象属性
- 将XML转换为普通的旧JavaScript对象
- 通过引用传递JavaScript对象
- javascript对象操作:根据指定条件选择属性
- Javascript对象类在单击时打开窗口进行颜色选择,并在更改时替换对象背景颜色
- 如何在异步函数中使用javascript对象
- 临时Javascript对象
- 如何在ASP中为用户控件添加Javascript对象网
- 使用数组向下搜索Javascript对象
- Rails将JavaScript对象存储到Model的有效方式
- JavaScript对象不是从原型链继承的
- 如何创建具有默认值的JavaScript对象字段?(AngularJS模型相关)
- SetInterval在javascript对象中表现怪异
- Javascript 对象和 this 关键字
- 如何在不知道关键字的情况下访问javascript对象值
- 在 JavaScript 对象中设置要使用的运算符的属性
- 如何搜索JavaScript对象并更改值