ES6解構嵌套對象

讓咱們先回憶一下ES6的對象解構,本文介紹各類ES6的對象解構用法,你用過哪種?javascript

最基本的解構

在對象中提取某個字段前端

const user = {
  id: 123,
  name: 'hehe'
};
const {name} = user;
console.log(name); //prints: hehe

解構並使用別名

有時接口定義的字段每每帶有下劃線,但咱們的前端更便好於駝峯式命名,那麼可使用別名(rename):java

const user = {
  id: 123,
  nick_name: 'hehe'
};
const {nick_name: nickName} = user;
console.log(nickName); //prints: hehe

解構嵌套對象

有時咱們會遇到嵌套對象,若是咱們瞭解未足夠多時,會寫出這種解構:code

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

沒錯,就是比別名方法多了一個{ }接口

若是沒有外層怎麼辦

假設要解構的數據是由接口返回的,因爲某種緣由會致使某個字段丟失。咱們會每每遇到這種意外:ip

const user = {
  id: 123,
  name: 'hehe'
};
const {education: {degree}} = user;  // TypeError: Cannot match against 'undefined' or 'null'.

這時你是否會以爲仍是咱們原始的方法好使:io

const education = user || {};
const degree = education.degree;

其實,神奇的解構可讓你定義一個缺省值,這樣,咱們不只能夠達到數據防護的目的,並且告別囉嗦的寫法了:console

const user = {
  id: 123,
  name: 'hehe'
};

const {
    education: {
        degree
    } = {}
} = user;
console.log(degree); //prints: undefined

這明顯是一股清流啊。ast

更深層次的對象怎麼辦?

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設置一個缺省值,可讀性更強,這又是一股清流。 在代碼中靈活使用解構不只可使代碼簡潔可讀,並且逼格大大提高。

相關文章
相關標籤/搜索