解構(gòu)嵌套對象

一、傳統(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;
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容