Method in JS to determine whether a field exists in JSON data


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

PS: about json operation, here again for you to recommend a few more practical json online tools for your reference:

Online JSON code verification, verification, beautification, formatting tools: (link: http://tools.jb51.net/code/json)

JSON online formatting tool: (link: http://tools.jb51.net/code/jsonformat)

Online XML/JSON interconversion tool: (link: http://tools.jb51.net/code/xmljson)

Json code online formatting/beautification/compression/editing/conversion tools: (link: http://tools.jb51.net/code/jsoncodeformat)

Online json compression/escape tool:

(link: http://tools.jb51.net/code/json\_yasuo\_trans)

C language style /HTML/CSS/json code format beautification tool: (link: http://tools.jb51.net/code/ccode\_html\_css\_json)