一、傳統(tǒng)方法,層層剝開
const user = {
id: 01,
name: 'Tom',
education: {
degree: 'Master'
}
}
const {education} = user;
const {degree} = education;
此方法比較低級、繁瑣,如果層比較深則極其繁瑣,代碼冗余。
二、一步到位
const user = {
id: 01,
name: 'Tom',
education: {
degree: 'Master'
}
}
const {education:{degree}} = user;
沒有外級時
假設(shè)要解構(gòu)的數(shù)據(jù)是由接口返回的,由于某種原因會導(dǎo)致某個字段丟失。我們會往往遇到這種意外:
const user = {
id: 01,
name: 'Tom'
}
const {education:{degree}} = user; // TypeError: Cannot match against 'undefined' or 'null'.
其實,神奇的解構(gòu)可以讓你定義一個缺省值,這樣,我們不僅可以達(dá)到數(shù)據(jù)防御的目的,而且告別啰嗦的寫法了:
const user = {
id: 01,
name: 'Tom'
}
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設(shè)置缺省值,但里面的school不存在,依然會報錯。
我們第一種辦法就是繼續(xù)對school設(shè)置缺省值為{}:
const user = {
id: 123,
name: 'hehe'
};
const {
education: {
school: {
name
} = {}
} = {}
} = user;
console.log(name); //prints: undefined
另一種辦法就是直接給education缺省值設(shè)置為{school: {}}:
const user = {
id: 123,
name: 'hehe'
};
const {
education: {
school: {
name
}
} = {school: {}}
} = user;
console.log(name); //prints: undefined
這兩種方法看似都可以,但如果要給學(xué)校名稱school.name一個缺省值呢?如果是第一種方法,會寫成這樣:
const user = {
id: 123,
name: 'hehe'
};
const {
education: {
school: {
name = 'NB'
} = {}
} = {}
} = user;
console.log(name); //prints: NB
你數(shù)數(shù)看,這有多少個“=”號嗎?啰嗦得不行,再看第二種方法:
const user = {
id: 123,
name: 'hehe'
};
const {
education: {
school: {
name
}
} = {
school: {
name: 'NB'
}
}
} = user;