LastTribunal
LastTribunal

Reputation: 1

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?

Upvotes: 11

Views: 45252

Answers (4)

Asif Uddin
Asif Uddin

Reputation: 36

Try "in" keyword

let dic = {1: 11, 2: 22};
if(1 in dic) console.log("found");
if(!(3 in dic)) console.log("not found");

Upvotes: 0

zhrist
zhrist

Reputation: 1558

In Nushorn Java script engine you can do also

if (dic.0) print('tested for null and key 0 exist')

Upvotes: 0

Entoarox
Entoarox

Reputation: 703

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.

Upvotes: 18

Jon
Jon

Reputation: 437664

Most of the time very simply, with

if (dic[1] === 11)

with one caveat: if the value you are looking for is undefined this will not do because it cannot distinguish between { 1: undefined } and just {}. In that case you need the more verbose test

if ('1' in dic && dic[1] === undefined)

Upvotes: 11

Related Questions