This article shares with you the methods and techniques for perfectly parsing data in JS. Friends who are interested in this can refer to it.
Since the separation of front-end and back-end, the data structures provided by some back-end partners have become increasingly confusing. They thought that the separation would reduce their burden and the quality of the interface would be very high, but human laziness was shown to be "perfect".
Because js is a type language, these errors often occur when using data
TypeError: Cannot read property 'xxx' of undefined TypeError: Cannot read property 'xxx' of null TypeError: xxx.map is not a function
And these exceptions are difficult to find, and they may not be discovered even if they are posted online in time. . Because these problems are caused by data anomalies. What if we elegantly solve or avoid these problems that affect the user experience?
// 第一种做法肯定是这样的 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 []
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
The problem and solution of {{}} flickering when vue renders
Method to obtain context parameter value using EL expression in JS
The above is the detailed content of How to perfectly parse data in js. For more information, please follow other related articles on the PHP Chinese website!