Can not validate "undefined" - JS

0

I have an object, where in some requests it returns without certain values.

The problem, when trying to validate the values, it generates error:

Note:Whenanalyzing,Inoticedthefollowingsituation:

Code:

vara={f:1}console.log(a)//{f:"Olha"}
console.log(a.b) //undefined
console.log(a.b.c) //Uncaught TypeError: Cannot read property 'c' of undefined at window.onload

The big problem is whether the previous value has not been set. Because it is a third-party API, I do not know which values can be set.

How do I validate in this type of situation?

Jsfiddle:

link

    
asked by anonymous 25.12.2017 / 17:15

1 answer

2

Following your example:

var a = {f : 1}
console.log(a)     // output: {f:1}
console.log(a.b)   // output: undefined
console.log(a.b.c) // Uncaught TypeError: Cannot read property 'c' of undefined

This is because "b" does not exist ( undefined ) logo "c" can not be a property ... so VM will throw a javascript .

To check if a given property exists in a Error using the {Object} statement you can use the if .

example :

var a = {f : 1}
//
if ('b' in a) {
    console.log(a.b)
}
if ('b' in a && 'c' in a.b) {
    console.log(a.b.c)
}

Within a subsequent block you could also use it as follows:

var a = {f : 1}
//
if ('b' in a) {
    // assumindo que existe a propriedade "b" no objeto "a"...
    if ('c' in a.b) {
        console.log(a.b.c)
    }
}

If you can not "know" whether or not the object will have all the bad properties you know the object should have a "pattern" perhaps the most appropriate would be to iterate over this object.     

25.12.2017 / 18:23