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)){}
There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.
Using the in Operator The in operator in JavaScript is used to determine if a certain property exists in an object or its inherited properties (also known as its prototype chain). If the provided property exists, the in operator returns true.
Use the underscore Library to Check if the Object Key Exists or Not in JavaScript. If we are already using any of the underscore library methods, we can use the _.has() method, as it returns true if that object has the provided key and returns false if not.
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")) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With