Is there an efficient way to do a case-insensitive JavaScript object property name lookup?

Doug Lerner picture Doug Lerner · Feb 5, 2016 · Viewed 9.7k times · Source

There is a certain object I have where the exact case of the properties is not known ahead of time. For example, a property name might be "AbC" or "Abc" or "abc", etc.

I do, however, know that only one exists. That is I know there can't be both a property "AbC" and also a property "abc".

The property name itself is case-sensitive. So if it is stored as theObject.Abc and I lookup theObject.abc I won't find the property.

In my object there might be 1,000 such properties.

It would be, possible, but inefficient, if each time I wanted to do a lookup I compared the lower-case value of the property I want to find against the lower-case value of the property names, like this:

propertyName = inputValue.toLowerCase();
for (var i in theObject) {
   if (propertyName == i.toLowerCase()); // found a matching property name
}

Does anybody know a cleverer way of doing this?

For reasons it would take too long to explain, I cannot just recreate the object and make all the properties lower-case. I do realize if that was possible I could just find

theObject['inputValue'.toLowerCase()]

directly. But as I said, I can't. The property names in theObject are what they are and they can't be changed. Asking me why would be a huge digression from the problem at hand. Please take my word for it that theObject is stuck with the property names it has.

Does anybody know an efficient way of doing a case-insensitive property name lookup in a situation like this?

Answer

HBP picture HBP · Feb 5, 2016

And going even further than Sigfried:

var theObject = {aBc: 1, BBA: 2, CCCa: 4, Dba: 3};

var lcKeys = Object.keys (theObject).reduce (
                          function (keys, k) { keys[k.toLowerCase()] = k; 
                                               return keys }, {});

function getValue (key) { return theObject[lcKeys[key.toLowerCase ()]] }

console.log (getValue ('abc'));
console.log (getValue ('Dba'));