美文网首页
解构嵌套对象

解构嵌套对象

作者: 如你眉间山水 | 来源:发表于2020-02-18 15:32 被阅读0次

一、传统方法,层层剥开

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;

相关文章

  • 3.解构赋值

    解构的分类 对象解构 数组解构 混合解构 解构参数 对象解构 解构赋值 嵌套对象解构 数组解构 数组解构 选择性的...

  • 解构赋值

    解构赋值 数组的解构赋值 嵌套,默认值,展开符 对象的解构赋值 对象解构赋值的本质与简写 对象解构的模式与变量 对...

  • 解构嵌套对象

    一、传统方法,层层剥开 此方法比较低级、繁琐,如果层比较深则极其繁琐,代码冗余。 二、一步到位 没有外级时 假设要...

  • 解构赋值

    解构赋值: 分解一个对象的结构 1.数组 2.复杂嵌套 3.对象解构的变量名 4.默认解构赋值 5.省略解构

  • es6学习-解构赋值

    解构赋值可以给默认值 为非同名局部变量赋值 嵌套对象解构 嵌套数组解构 不定元素 与函数参数一样,不定元素必须为最...

  • <<深入理解ES6>>记:五

    第5章 解构:使数据访问更便捷 1.对象解构 允许默认值 为不同名局部变量赋值 嵌套对象解构 2.数组解构 3.不...

  • 数组解构、混合结构以及参数结构

    《深入理解ES6》阅读随笔 数组解构 数组解构跟对象解构类似,同样具有数据提取、解构赋值、设置默认值、嵌套解构等特...

  • ES6解构赋值学习笔记

    数组的解构 可嵌套 可忽略 不完全解构 剩余运算符 字符串等在数组的解构中,解构的目标若为可遍历对象,皆可进行解构...

  • Kotlin —  Destructuring Declarat

    什么是解构? 解构是从存储在(可能是嵌套的)对象和数组中的数据中提取多个值的一种便捷方式。 有时候,将对象拆分为多...

  • ES6 解构赋值

    嵌套结构的对象解构,有以下几种常见的几种变体: es6解构赋值讲的比较详细的一篇文章:https://segmen...

网友评论

      本文标题:解构嵌套对象

      本文链接:https://www.haomeiwen.com/subject/fnpgfhtx.html