Home > Web Front-end > JS Tutorial > body text

How to determine whether a field exists in the passed JSON data in JS_javascript skills

WBOY
Release: 2016-05-16 16:39:21
Original
1299 people have browsed it

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!