This article mainly introduces how to determine whether a field exists in the transmitted JSON data in JS. If you need it, you can refer to how to determine whether a field exists in the transmitted JSON data,
1. obj ["key"]! = Undefined
This is flawed. If the key is defined and the value of 2 is undefined, a problem will occur.
2 .! ("Key" in obj)
3. obj. hasOwnProperty ("key ")
The two methods are better. We recommend that you use them.
Original answer:
Actually, checking for undefined-ness is not an accurate way of testing whether a key exists. What if the key exists but the value is actually undefined?
Var obj = {key: undefined };
Obj ["key"]! = Undefined // false, but the key exists!
You shoshould instead use the in operator:
"Key" in obj // true, regardless of the actual value
If you want to check if a key doesn't exist, remember to use parenthesis:
! ("Key" in obj) // true if "key" doesn't exist in object
! "Key" in obj // ERROR! Equivalent to "false in obj"
Or, if you want to maid test for properties of the object instance (and not inherited properties), usehasOwnProperty:
Obj. hasOwnProperty ("key") // true