问题描述
基于条件,我正在像这样更改对象值。有没有更好的方法来进行波纹管检查,而无需重复零件?
if (this.selected.id === productId) {
this.obj1 = {
...this.product,tags: this.selected.tags,imgs: product.imgs,}
} else {
this.obj1 = {
...this.product,imgs: [],}
}
如何更好地优化上述解决方案,例如与?内联条件运算符? 或类似的东西:
this.selected.id === productId ? imgs: product.imgs
否则不要添加此属性和值
解决方法
是的,如果您使用内联ternary operator并且不重复其余代码,看起来会更好:
this.obj1 = {
...this.product,tags: this.selected.tags,imgs: this.selected.id === productId ? product.imgs: [],}
编辑: 如果您不希望在不满足条件的情况下不做任何事情:
this.obj1 = {
...this.product,tags: this.selected.tags
}
if(this.selected.id === productId){
this.obj1.imgs = product.imgs
}