鍍金池/ 問答/HTML/ js對象如何優(yōu)雅的取一個深度的值?

js對象如何優(yōu)雅的取一個深度的值?

問題描述

比如后臺可能返回一個對象

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:''):''):''):'';

這顯然可讀性不好,也麻煩,請問有什么方式可以優(yōu)雅的處理這種取值

并且防止Cannot read property 'xxx' of undefined 的報錯嗎

回答
編輯回答
孤星
2017年1月17日 17:04
編輯回答
掛念你

lodash/get 了解一下,_.get(obj,'school.class1.student', undefined), lodash/get

2017年3月4日 08:02
編輯回答
玩控

利用邏輯運算的特性可以很優(yōu)雅的解決!

obj.school.class1 && obj.school.class1.student
2017年11月2日 04:06
編輯回答
怣人

如果不用考慮兼容性的話,加個Proxy監(jiān)聽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._)//50
console.log(getter(obj).school1.class11.student._)//undefined
2017年4月5日 16:14
編輯回答
愿如初

如果是我,我會這么做。let student = obj&&obj.school&&&obj.school.class1&&obj.school.class1.student
希望對你有幫助

2017年10月23日 08:24
編輯回答
心上人

樓主你好!可以使用以下方法來做防御性編程。

function getIn(p, o) {
  return p.reduce(function(xs, x) {
    return (xs && xs[x]) ? xs[x] : null;
  }, o);
}

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

var student = getIn(['school', 'class1', 'student'], obj);
console.log(student);
// 50

此方法是參照Facebook的immutable里的編寫的。函數(shù)庫 ramdajs也有類似的方法,可自行查找。

2017年4月3日 05:45
編輯回答
挽青絲
const defaultObj = {
  school: {
    class1: {
      student: ''
    }
  }
}
let obj1 = {
  school: {
    class1: {
      student: 50
    }
  }
}
let obj2 = Object.assign({}, defaultObj, obj1) // obj2.school.class1是50
obj2 = Object.assign({}, defaultObj, undefined) // obj2.school.class1是''
obj2 = Object.assign({}, defaultObj, null) // obj2.school.class1是''
obj2 = Object.assign({}, defaultObj, {}) // obj2.school.class1是''
let student = obj2.school.class1
2018年6月8日 22:01
編輯回答
澐染
function safeProps(func, defaultVal) {
    try {
        return func();
    } catch (e) {
        return defaultVal;
    }
}

safeProps(function(){
    student = obj.school.class1.student
}, -1)
2018年3月29日 05:36