讓我們先回憶一下ES6的物件解構,本文介紹各種ES6的物件解構用法,你用過哪一種?
最基本的解構
在物件中提取某個欄位
const user = {
id: 123,
name: `hehe`
};
const {name} = user;
console.log(name); //prints: hehe
解構並使用別名
有時介面定義的欄位往往帶有下劃線,但我們的前端更便好於駝峰式命名,那麼可以使用別名(rename):
const user = {
id: 123,
nick_name: `hehe`
};
const {nick_name: nickName} = user;
console.log(nickName); //prints: hehe
解構巢狀物件
有時我們會遇到巢狀物件,如果我們瞭解未足夠多時,會寫出這種解構:
const user = {
id: 123,
name: `hehe`,
education: {
degree: `Masters`
}
};
// 假設我們要提取degree
const {education} = user;
const {degree} = education;
我們會寫兩行,一層層的剝開,明顯繁瑣,如果這個物件有三四層結構那簡直無法入目。其實可以用解構一步到位的:
const user = {
id: 123,
name: `hehe`,
education: {
degree: `Masters`
}
};
const {education: {degree}} = user;
console.log(degree); //prints: Masters
沒錯,就是比別名方法多了一個{ }
如果沒有外層怎麼辦
假設要解構的資料是由介面返回的,由於某種原因會導致某個欄位丟失。我們會往往遇到這種意外:
const user = {
id: 123,
name: `hehe`
};
const {education: {degree}} = user; // TypeError: Cannot match against `undefined` or `null`.
這時你是否會覺得還是我們原始的方法好使:
const education = user || {};
const degree = education.degree;
其實,神奇的解構可以讓你定義一個預設值,這樣,我們不僅可以達到資料防禦的目的,而且告別囉嗦的寫法了:
const user = {
id: 123,
name: `hehe`
};
const {
education: {
degree
} = {}
} = user;
console.log(degree); //prints: undefined
這明顯是一股清流啊。
更深層次的物件怎麼辦?
const user = {
id: 123,
name: `hehe`
};
const {
education: {
school: {
name
}
} = {}
} = user; // TypeError: Cannot match against `undefined` or `null`.
這裡外層對education設定預設值,但裡面的school不存在,依然會報錯。
我們第一種辦法就是繼續對school設定預設值為{}:
const user = {
id: 123,
name: `hehe`
};
const {
education: {
school: {
name
} = {}
} = {}
} = user;
console.log(name); //prints: undefined
另一種辦法就是直接給education預設值設定為{school: {}}:
const user = {
id: 123,
name: `hehe`
};
const {
education: {
school: {
name
}
} = {school: {}}
} = user;
console.log(name); //prints: undefined
這兩種方法看似都可以,但如果要給學校名稱school.name一個預設值呢?如果是第一種方法,會寫成這樣:
const user = {
id: 123,
name: `hehe`
};
const {
education: {
school: {
name = `NB`
} = {}
} = {}
} = user;
console.log(name); //prints: NB
你數數看,這有多少個“=”號嗎?囉嗦得不行,再看第二種方法:
const user = {
id: 123,
name: `hehe`
};
const {
education: {
school: {
name
}
} = {
school: {
name: `NB`
}
}
} = user;
console.log(name); //prints: NB
這樣整體給education設定一個預設值,可讀性更強,這又是一股清流。
在程式碼中靈活使用解構不僅可以使程式碼簡潔可讀,而且逼格大大提升。