javascript - Typescript - 物件的條件屬性
我有以下對象,我希望為其設置條件屬性:
{ name: this.username, DOB: new Date(this.inputDate)}
假設我希望新增一個名為 gender 的第三個屬性,如果使用者已經指定了他們的性別。以下的正確語法應該是什麼?
{ name: this.username, DOB: new Date(this.inputDate), if(this.userGender) gender: this.userGender}
附註:如果我的物件中沒有對應的值,我不想擁有 gender 屬性。所以我該如何僅在條件滿足時才建立該屬性呢?
答案#1
理想情況下,你只需要在宣告物件之後,作為第二個動作添加適當的屬性。就像這樣:
const myObj = {
name: this.username,
DOB: new Date(this.inputDate),
}
if(this.userGender) myObj.gender = this.userGender;
然而,有時候將「可選」屬性與其他屬性一起直接宣告也是不錯的,這種情況下你可以使用物件展開運算符來達到你想要的效果:
const myObj = {
name: this.username,
DOB: new Date(this.inputDate),
...this.userGender && { gender: this.userGender }
}
答案#2
這樣也可以做到,更乾淨且易讀。
const myObj = {
name: this.username,
DOB: new Date(this.inputDate),
...(this.userGender && { gender : this.userGender })
}