为了账号安全,请及时绑定邮箱和手机立即绑定

js对象如何优雅的取一个深度的值?

js对象如何优雅的取一个深度的值?

BIG阳 2018-12-18 22:16:18
问题描述比如后台可能返回一个对象let obj = {     school: {       class1: {         student: 50       }     }}我需要取出里面student的值,但是有可能后台返回给我的是 {school: null} 或者 {} 甚至是 undefined因此我取值时可能是let student = obj?(obj.school?(obj.school.class1?(obj.school.class1.studnet?obj.school.class1.studnet:''):''):''):'';这显然可读性不好,也麻烦,请问有什么方式可以优雅的处理这种取值并且防止Cannot read property 'xxx' of undefined 的报错吗
查看完整描述

1 回答

?
慕的地10843

TA贡献1785条经验 获得超8个赞

如果不用考虑兼容性的话,加个Proxy监听get是个很合适的办法

/**
 * @param target
 * @param exec 取值属性
 * @returns {*}
 */function getter(target, exec = '_') {  return new Proxy({}, {    get: (o, n) => {      return n === exec ?
        target :
        getter(typeof target === 'undefined' ? target : target[n], exec)
    }
  });
}

let obj = {
  school: {
    class1: {
      student: 50
    }
  }
};console.log(getter(obj).school.class1.student._)//50console.log(getter(obj).school1.class11.student._)//undefined


查看完整回答
反对 回复 2018-12-18
  • 1 回答
  • 0 关注
  • 606 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信