Skip to content
Advertisement

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?

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement