Unable to validate "Undefined" - JS

Asked

Viewed 53 times

0

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

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

inserir a descrição da imagem aqui

Note: When analyzing, I realized the following situation:

Code:

var a = {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 don’t know if which values can be set.

How do I validate in this type of situation?

Jsfiddle:

https://jsfiddle.net/o5w1nd2L/

  • Apparently your error reports that the property does not exist or is "null" speed... consider adding to your question the relevant part of the code in question in this way it will be more likely that you actually get a satisfactory answer.

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" there is no (undefined) soon "c" can’t be a property... so the VM of javascript launched a Error.

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

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 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 cannot "know" whether or not the object will have all the bad properties you know that the object should have a "pattern" perhaps the most indicated would be to iterate on this object.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.