Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a javascript object has a certain property

Suppose I have a javascript object like this:

window.config
config.UI = {
        "opacity": {
            "_type": "float",
            "_tag": "input",
            "_value": "1",
            "_aka": "opacity",
            "_isShow":"1"
 }

How can I judge if the "opacity" object has a property named "_test"? like

var c=config.ui.opacity;
for(var i in c)
{
   //c[i]=="_test"?
}

How do I find out if it's assigned as well?

like image 655
hh54188 Avatar asked Dec 09 '22 01:12

hh54188


1 Answers

There are at least three ways to do this; which one you use is largely up to you and sometimes even a matter of style, though there are some substantive differences:

if..in

You can use if..in:

if ("_test" in config.UI.opacity)

...because when used in a test (as opposed to the special for..in loop), in tests to see if the object or its prototype (or its prototype's prototype, etc.) has a property by that name.

hasOwnProperty

If you want to exclude properties from prototypes (it doesn't much matter in your example), you can use hasOwnProperty, which is a function all objects inherit from Object.prototype:

if (config.UI.opacity.hasOwnProperty("_test"))

Just retrieve it and check the result

Finally, you can just retrieve the property (even if it doesn't exist) and the decide what to do with the result by looking at the result; if you ask an object for the value of a property it doesn't have, you'll get back undefined:

var c = config.UI.opacity._test;
if (c) {
    // It's there and has a value other than undefined, "", 0, false, or null
}

or

var c = config.UI.opacity._test;
if (typeof c !== "undefined") {
    // It's there and has a value other than undefined
}

Being defensive

If it's possible that config.UI won't have an opacity property at all, you can make all of those more defensive:

// The if..in version:
if (config.UI.opacity && "_test" in config.UI.opacity)

// The hasOwnProperty version
if (config.UI.opacity && config.UI.opacity.hasOwnProperty("_test"))

// The "just get it and then deal with the result" version:
var c = config.UI.opacity && config.UI.opacity._test;
if (c) { // Or if (typeof c !== "undefined") {

That last one works because the && operator is particularly powerful in JavaScript compared with some other languages; it's the corollary of the curiously-powerful || operator.

like image 190
T.J. Crowder Avatar answered Mar 07 '23 00:03

T.J. Crowder