has been disorganized by the back-end separation, and the data structure given by some back-end small partners. Thinking that separation reduces the quality of their burden interface is very high, but human inertia is "perfect".

JS is due if the type of language, so when using the data often appear the error

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

, and these abnormalities are difficult to find, timely on-line are not necessarily found. Because these problems are caused by data anomalies. What if an elegant solution or avoidance of these problems affect the user experience?

 / / the first approach is certainly the case of if (a) {return a.name} '||' didn't you name / / this approach simple can make do with, but if you encounter such a user.country.area.city.name, don't have to write like that if (user & & user.country; & & user.country.area & & user.country.area.city) {return user.country.area.city.name} '||' didn't you name / / this is a painful thing @ / / second brothers back, thanks to ES6 let {country={area:{city:{name:'you didn't name'}}}} = user; this feeling is not very good solution / third, construct an analytic function by reduce (obj, function getValue key return (key.split) {.Reduce (function') (O, K) {/ / O / / key, the current object array, the next element if ((typ EOF o'undefined'o || = = = = = = null) {return k.indexOf ('[array]'))! = = -1? []: O ('[array]')}else{return k.indexOf -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'}}]} = {country:{} let user5 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.lo) G (getValue (user5,'country.city[array].1.name') (console.log) getValue (user5,'country.city[array].persion[array]')) / / output undefined undefined "12312" [1, 2 3], 2 undefined undefined 

[] code test: https://jsbin.com/zoberem/edit console

? JS, finally on the front of the abnormal report, this is a big the direction of research, there are also some solutions, but I didn't find the real promotion.


This concludes the body part

This paper fixed link:http://www.script-home.com/how-to-parse-the-data-perfectly-in-js.html | Script Home | +Copy Link

Article reprint please specify:How to parse the data perfectly in JS | Script Home

You may also be interested in these articles!