解构嵌套对象

一、传统方法,层层剥开

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;

没有外级时

假设要解构的数据是由接口返回的,由于某种原因会导致某个字段丢失。我们会往往遇到这种意外:

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

其实,神奇的解构可以让你定义一个缺省值,这样,我们不仅可以达到数据防御的目的,而且告别啰嗦的写法了:

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设置缺省值,但里面的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;

你可能感兴趣的:(解构嵌套对象)