In Javascript Can An Object Have Case Insensitive Member Access?
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 = 'B
Solution 1:
You could take a proxy and address the property directly with the lower case value of the key.
var foo = {},
proxy = newProxy(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);
Solution 2:
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.
classMyObject {
constructor() {
// Some property that we want to usethis.bar = 'abc'// Return a new proxyreturnnewProxy(this, {
get: (target, prop) => target[prop.toLowerCase()],
set: (target, prop, value) => (target[prop.toLowerCase()] = value)
})
}
}
var foo = newMyObject()
foo.Bar = "Baz"console.log(foo.bAR)
Post a Comment for "In Javascript Can An Object Have Case Insensitive Member Access?"