EN
JavaScript - access property case-insensitively
1
answers
0
points
How can I specify an object's property by name regardless of case?
Let's say I have an object:
var myObject = { id: 1, name: 'Ann' };
I need to access a property of that object dynamically, for example:
function setter(object, property, value) {
object[property] = value;
}
Now, I want the property to be case insensitive in case the property name is passed into the function as e.g. ID instead of id.
1 answer
0
points
Use toLowerCase() or toUpperCase() method to convert both strings to the same case and then compare them.
Practical example
In this example, we create a reusable function that converts property argument to lower case and compare it with given object property names also converted to lower case.
// ONLINE-RUNNER:browser;
var hasOwnProperty = Object.prototype.hasOwnProperty;
function setProperty(object, key, value) {
var tmp = key.toLowerCase();
for (var item in object) {
if (hasOwnProperty.call(object, item) && tmp === item.toLowerCase()) {
object[item] = value;
return;
}
}
}
// Usage example:
var myObject = { id: 1, name: 'Ann' };
setProperty(myObject, 'ID', 2);
console.log(JSON.stringify(myObject)); // { id: 2, name: 'Ann' }
Warning:
This solution assums, that the object doesn't contain multiple properties with the same keys in different cases (e.g.
var myObject = { id: 1, ID: 2 }).
See also
References
0 comments
Add comment