猿问

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

问题描述

比如后台可能返回一个对象

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 的报错吗


BIG阳
浏览 646回答 1
1回答

慕的地10843

如果不用考虑兼容性的话,加个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
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答