Reputation: 8270
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)
Upvotes: 0
Views: 205
Reputation: 36341
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)
Upvotes: 4
Reputation: 386736
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);
Upvotes: 4