Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)){} 
like image 382
user2065483 Avatar asked Jun 15 '13 18:06

user2065483


People also ask

How do you check if a key exists in an object JavaScript?

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.

How do you check if a key value pair exists in an object JavaScript?

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.

How do you check if a key does not exist in an object JavaScript?

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.


2 Answers

Use the in operator:

testArray = 'key1' in obj; 

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

like image 115
Sirko Avatar answered Sep 25 '22 20:09

Sirko


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")) {   ... } 
like image 37
Guffa Avatar answered Sep 22 '22 20:09

Guffa