How does the js object gracefully take a depth value?

problem description

for example, the background may return an object

let obj = {
    school: {
      class1: {
        student: 50
      }
    }
}

I need to take out the value of student in it, but it is possible that {school: null} or {} or even undefined

is returned to me by the background.

so when I take a value, it may be

let student = obj?(obj.school?(obj.school.class1?(obj.school.class1.studnet?obj.school.class1.studnet:""):""):""):"";

this is obviously not readable and troublesome. Is there any way to deal with this value gracefully

and prevent Cannot read property "xxx" of undefined from reporting errors

Nov.26,2021

function safeProps(func, defaultVal) {
    try {
        return func();
    } catch (e) {
        return defaultVal;
    }
}

safeProps(function(){
    student = obj.school.class1.student
}, -1)

adding Proxy listening get is a very appropriate method if compatibility is not considered.

/**
 * @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._)//50
console.log(getter(obj).school1.class11.student._)//undefined

lodash/get find out, _ .get (obj,'school.class1.student', undefined), lodash/get


Hello, landlord! You can use the following methods to do defensive programming .

  

if it were me, I would do this. Let student = obj&&obj.school&obj.school.class1&&obj.school.class1.student
I hope it will be helpful to you

Menu