让咱们先回忆一下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设置一个缺省值,可读性更强,这又是一股清流。 在代码中灵活使用解构不只可使代码简洁可读,并且逼格大大提高。