js中如何完美的解析数据
自从有了前后端分离,一些后端小伙伴给出的数据结构也来越混乱了。以为分离减轻了他们的负担接口的质量会非常高但是人的惰性却体现的很“完美”。
由于js是若类型的语言,所以在使用数据的时候经常会出现这个几个错误
TypeError:Cannotreadproperty'xxx'ofundefined TypeError:Cannotreadproperty'xxx'ofnull TypeError:xxx.mapisnotafunction
而这些异常很难发现,及时发上线了都不一定能发现。因为这些问题都是由于数据异常导致的。如果优雅的解决或者说避免这些问题影响到用户体验呢?
//第一种做法肯定是这样的
if(a){
returna.name||'你没名字'
}
//这种做法处理简单的还能凑合用,但是如果你遇到这样的呢user.country.area.city.name,难道要这样写
if(user&&user.country&&user.country.area&&user.country.area.city){
returnuser.country.area.city.name||'你没名字'
}
//这是多么痛苦的一件事情@后端兄弟
//第二种,感谢es6
let{country={area:{city:{name:'你没名字'}}}}=user;
这个感觉也不是很好的解决方案
//第三种,利用reduce构建一个解析函数
functiongetValue(obj,key){
returnkey.split('.').reduce(function(o,k){
//o,当前对象
//key,数组下一个元素
if((typeofo==='undefined'||o===null)){
returnk.indexOf('[array]')!==-1?[]:o
}else{
returnk.indexOf('[array]')!==-1?(o[k.replace('[array]','')]||[]):o[k]
}
},obj)
}
letuser1;
letuser2={
}
letuser3={
country:{
area:{
city:{
name:'12312'
}
}
}
}
letuser4={
country:[
{
city:{
name:'12312'
}
}
]
}
letuser5={
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
[]
代码测试:https://jsbin.com/zoberem/edit?js,console
最后关于前端异常上报,这是一个很大的研究方向,市面上也有一些解决方案,但是真正推广的我目前没发现。