In JS, how does one determine whether a field exists in the transmitted JSON data?

Source: Internet
Author: User
Tags hasownproperty

In JS, how does one determine whether a field exists in the transmitted JSON data?

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


How can I determine whether a field exists when jsoncpp reads a json file?

If (value ["sex"]. isNull ()... is to check whether a key name exists in the array.

 
After Jquery flexigird obtains json data, it cannot be determined on the foreground. If a field is the same, do some operations?

Json is sent to the front-end. It looks like it's playing. I don't know why it's called json. But js is javascript, your task is to export the json to the foreground.
2. Find the field you want, for example, mJson ['name'] = "zhangsan" (in one dimension)
MyJSONObject. arr1 [0]. name = "Zhang San" (two-dimensional)
Are there any other things that you can't do?

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.