0

I would like a Javascript class that acts pretty much like an ordinary object in its expando capability but with case insensitive access. So

var foo = new MyObject();
foo.Bar = "Baz";
alert (foo.bAR) ;   // I want this not to error but to be forgiving and print Baz

Javascript is not my main development language so I am not familiar with guts of the language. Is there a fancy way of using prototypes perhaps?

Sorry, also stuck on an old version of Javascript I should mention (dunno for sure possible version 3)

S Meaden
  • 8,050
  • 3
  • 34
  • 65
  • 1
    Possible duplicate of [Access JavaScript property case-insensitively?](https://stackoverflow.com/questions/12484386/access-javascript-property-case-insensitively) – Wiktor Zychla Aug 16 '19 at 20:25
  • 1
    Do NOT do this. Stop providing mechanisms to allow sloppy development. Keys are case sensitive. If you allow someone else to use a key with different case then you are allowing them to create crappy code that is difficult to maintain, not to mention slower since you have to run special code to allow the keys to match when they should not. – Intervalia Aug 16 '19 at 20:35
  • Related: [Are javascript object keys case-sensitive?](https://stackoverflow.com/q/42400548/1048572), [Access JavaScript property case-insensitively?](https://stackoverflow.com/q/12484386/1048572), [Is the hasOwnProperty method in JavaScript case sensitive?](https://stackoverflow.com/q/5832888/1048572) – Bergi Dec 14 '20 at 21:28

2 Answers2

4

You can do this using a Proxy.

In the proxy, we convert the key that we are searching for to lowercase and the objects keys to lowercase and look for the property in the target.

class MyObject {
  constructor() {
    // Some property that we want to use
    this.bar = 'abc'

    // Return a new proxy
    return new Proxy(this, {
      get: (target, prop) => target[prop.toLowerCase()],
      set: (target, prop, value) => (target[prop.toLowerCase()] = value)
    })
  }
}

var foo = new MyObject()
foo.Bar = "Baz"
console.log(foo.bAR)
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
4

You could take a proxy and address the property directly with the lower case value of the key.

var foo = {},
    proxy = new Proxy(foo, {
        get: function(obj, prop) {
            return obj[prop.toLowerCase()];
        },
        set: function(obj, prop, value) {
            obj[prop.toLowerCase()] = value;
        }
    });

proxy.Bar = "Baz";

console.log(proxy.bAR);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392