Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently check if a Key Value pair exists in a Javascript "dictionary" object

Given:

        var dic = {1: 11, 2: 22}

How to test if (1, 11) exists?

like image 915
LastTribunal Avatar asked Dec 18 '13 21:12

LastTribunal


People also ask

How do you check if a key value pair exists in a dictionary 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 value is present in an object in JavaScript?

The hasOwnProperty() method will check if an object contains a direct property and will return true or false if it exists or not. The hasOwnProperty() method will only return true for direct properties and not inherited properties from the prototype chain.

How do you check if a key has a value in JavaScript?

Use the in operator to check if a key exists in an object, e.g. "key" in myObject . The in operator will return true if the key is present in the object, otherwise false is returned. Copied! The syntax used with the in operator is: string in object .

How do you check if a key exists in a JavaScript array?

Using the indexOf() Method JavaScript's indexOf() method will return the index of the first instance of an element in the array. If the element does not exist then, -1 is returned.


1 Answers

If you need to check both if the key exists, and has a value, the below piece of code would work best:

function hasKeySetTo(obj,key,value)
{
    return obj.hasOwnProperty(key) && obj[key]==value;
}

It only returns true if obj has a key called key and that key has value as its value.

like image 132
Entoarox Avatar answered Sep 25 '22 17:09

Entoarox