「身無綵鳳雙飛翼,心有靈犀一點通。」javascript
如今開始寫代碼o(╯□╰)ojava
//正常的數據結構
const user = {
id: 1,
email: 'carlo@bingshan.com',
info: {
name: 'carlo',
address: {
country: 'china',
provinces: 'liaoning',
city: 'dalian',
street: 'aaaaaaaa'
}
}
}
//缺失一部分
const user = {
id: 1,
email: 'carlo@bingshan.com',
info: {
name: 'carlo'
}
}
console.log(user.info.address.city);
//TypeError: Cannot read property 'city' of undefined
複製代碼
if(user && user.info && user.info.address && user.info.address.city) {
let cityStr = user.info.address.city;
}else{
}
//或者
let cityStr = user && user.info && user.info.address ? user.info.address.city : '';
複製代碼
好長好複雜好low!!!git
使用或運算github
let cityStr = (((user || {}).info || {}).address || {}).city;
複製代碼
仍是很長!!數組
抽出一個公共方法來判斷好了安全
function checkObjSafe(obj) {
for (let i = 1; i < arguments.length; i++) {
if (!obj.hasOwnProperty(arguments[i])) {
return false;
}
obj = obj[arguments[i]];
}
return true;
}
console.log(checkObjSafe(user,'info','address','city'))
複製代碼
for循環明顯不是個人風格!!bash
function checkObjSafe(obj, level, ...rest) {
if (obj === undefined) return false
if (rest.length == 0 && obj.hasOwnProperty(level)) return true
return checkObjSafe(obj[level], ...rest)
}
console.log(checkObjSafe(user,'info','address'))
複製代碼
ES6彷佛好了一點~數據結構
function checkObjSafe(obj, keys) {
let rest = keys.shift();
return obj[rest] && (!keys.length || checkObjSafe(obj[rest], keys));
}
console.log(checkObjSafe(user,['info','address','city']))
複製代碼
試試扔個數組進去ui
function checkObjSafe(obj, s){
s= s.split('.')
var objNew= obj[s.shift()];
while(objNew && s.length) objNew= objNew[s.shift()];
return objNew;
}
console.log(checkObjSafe(user,'info.address.city'))
複製代碼
貌似方便了很多,直接傳入字符串就行spa
ES6大法好
function checkObjSafe( obj, ...keys ) {
return keys.reduce( ( a, b ) => ( a || { } )[ b ], obj );
}
console.log(checkObjSafe(user,'info','address','city'))
複製代碼
暴力風格
try {
let cityStr = user.info.address.city;
} catch (error) {
let cityStr = undefined;
}
複製代碼
_.get(user,'info.address.city')
複製代碼
const test = user?.info?. address?. city;
//目前處在Stage 2階段,可參考下面的連接⤵️
複製代碼