js中如何優雅的解析數據

自從有了先後端分離,一些後端小夥伴給出的數據結構也來越混亂了。覺得分離減輕了他們的負擔接口的質量會很是高可是人的惰性卻體現的很「完美」。
因爲js是若類型的語言,因此在使用數據的時候常常會出現這個幾個錯誤前端

TypeError: Cannot read property 'xxx' of undefined
TypeError: Cannot read property 'xxx' of null
TypeError: xxx.map is not a function

而這些異常很難發現,及時發上線了都不必定能發現。由於這些問題都是因爲數據異常致使的。若是優雅的解決或者說避免這些問題影響到用戶體驗呢?es6

// 第一種作法確定是這樣的
if(a){
   return a.name || '你沒名字'
}
// 這種作法處理簡單的還能湊合用,可是若是你遇到這樣的呢 user.country.area.city.name,難道要這樣寫
if(user && user.country && user.country.area && user.country.area.city){
    return user.country.area.city.name || '你沒名字'
}
// 這是多麼痛苦的一件事情 @後端兄弟

// 第二種,感謝es6
let {country={area:{city:{name:'你沒名字'}}}} = user;
這個感受也不是很好的解決方案

// 第三種,利用reduce構建一個解析函數
function getValue(obj,key){
    return key.split('.').reduce(function(o,k){
        // o,當前對象
        // key,數組下一個元素
        if((typeof o === 'undefined' || o === null)){
           return k.indexOf('[array]') !== -1?[]:o
        }else{
           return k.indexOf('[array]') !== -1?(o[k.replace('[array]','')]||[]):o[k]
        }
    },obj)
}

let user1;

let user2 = {
  
}

let user3 = {
  country:{
    area:{
      city:{
        name:'12312'
      }
    }
  }
}
let user4 = {
  country:[
    {
      city:{
        name:'12312'
      }
    }
  ]
}

let user5 = {
  country:{
    city:[1,2,3]
  }
}

console.log(getValue(user1,'country.area.city.name'))

console.log(getValue(user2,'country.area.city.name'))

console.log(getValue(user3,'country.area.city.name'))

console.log(getValue(user5,'country.city[array]'))
console.log(getValue(user5,'country.city[array].1'))
console.log(getValue(user5,'country.city[array].10'))
console.log(getValue(user5,'country.city[array].1.name'))
console.log(getValue(user5,'country.city[array].persion[array]'))

// 輸出結果
undefined
undefined
"12312"
[1, 2, 3]
2
undefined
undefined
[]

測試代碼後端

最後關於前端異常上報,這是一個很大的研究方向,市面上也有一些解決方案,可是真正推廣的我目前沒發現。數組

相關文章
相關標籤/搜索