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

  • 2020-03-30 02:19:16
  • 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.


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:

JSON online formatting tool:

Online XML/JSON interconversion tool:

Json code online formatting/beautification/compression/editing/conversion tools:

Online json compression/escape tool:


C language style /HTML/CSS/json code format beautification tool:

Related articles: