How to determine whether a field _ javascript exists in the transmitted JSON data in JS?

Source: Internet
Author: User
Tags hasownproperty
This article mainly introduces how to determine whether a field exists in the transmitted JSON data in JS. If you need it, you can refer to how to determine whether a field exists in the transmitted JSON data,

1. obj ["key"]! = Undefined

This is flawed. If the key is defined and the value of 2 is undefined, a problem will occur.

2 .! ("Key" in obj)
3. obj. hasOwnProperty ("key ")

The two methods are better. We recommend that you use them.

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 shoshould 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 maid test for properties of the object instance (and not inherited properties), usehasOwnProperty:

Obj. hasOwnProperty ("key") // true

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.