Home >Web Front-end >JS Tutorial >How to determine whether a field exists in the passed JSON data in JS_javascript skills
How to determine whether a certain field exists in the JSON data passed in?
1.obj["key"] != undefined
This is defective. If the key is defined and the value is very often undefined, then there will be a problem with this sentence.
2.!("key" in obj)
3.obj.hasOwnProperty("key")
These two methods are better and recommended.
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 should 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 particularly test for properties of the object instance (and not inherited properties), usehasOwnProperty:
obj.hasOwnProperty("key") // true