[英]How to conditionally change object property value in the better way then this solution in JS?
根據條件,我正在像這樣更改對象值。 有沒有更好的方法來進行波紋管檢查而沒有重復的零件?
if (this.selected.id === productId) {
this.obj1 = {
...this.product,
tags: this.selected.tags,
imgs: product.imgs,
}
} else {
this.obj1 = {
...this.product,
tags: this.selected.tags,
imgs: [],
}
}
如何可以更優化上述解決方案,例如使用? 具有內聯條件的運算符? 或者像這樣:
this.selected.id === productId ? imgs: product.imgs
this.selected.id === productId ? imgs: product.imgs
否則不添加此屬性和值
是的,如果您使用內聯三元運算符並且不重復其余代碼,它看起來會更好:
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.