How do you determine whether there is a field in the JSON data passed in JS
- 2020-03-30 03:42:13
- OfStack
How to determine whether a field exists in the JSON data that's being sent to you,
1. The obj [" key "]! = is undefined
This is flawed, and if this key is defined, and it's a very 2 value assigned to undefined, then this sentence is going to be a problem.
2.! (" key "obj) in
3. Obj. HasOwnProperty (" key ")
These two methods are better, recommended to use.
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 should use the in operator instead:
"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 particularly test for properties of the object instance (and not inherited properties), usehasOwnProperty:
Obj. HasOwnProperty (" key ") / / true