Skip to content
Advertisement

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)){}

Advertisement

Answer

Use the in operator:

testArray = 'key1' in obj;

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

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement