Checking if a key exists in a JS object

I have the following JavaScript object:

var obj = {
    "key1" : val,
    "key2" : val,
    "key3" : val
}

Is there a way to check if a key exists in the array, similar to this?

testArray = jQuery.inArray("key1", obj);

does not work.

Do I have to iterate through the obj like this?

jQuery.each(obj, function(key,val)){}

Use the in operator:

testArray = 'key1' in obj;

Sidenote: What you got there, is actually no jQuery object, but just a plain JavaScript Object.


That's not a jQuery object, it's just an object.

You can use the hasOwnProperty method to check for a key:

if (obj.hasOwnProperty("key1")) {
  ...
}

var obj = {
    "key1" : "k1",
    "key2" : "k2",
    "key3" : "k3"
};

if ("key1" in obj)
    console.log("has key1 in obj");

=========================================================================

To access a child key of another key

var obj = {
    "key1": "k1",
    "key2": "k2",
    "key3": "k3",
    "key4": {
        "keyF": "kf"
    }
};

if ("keyF" in obj.key4)
    console.log("has keyF in obj");
链接地址: http://www.djcxy.com/p/26644.html

上一篇: 我如何获得git commit中的文件列表?

下一篇: 检查一个JS对象中是否存在一个键