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:
xxxxxxxxxx
1
var myObject = { id: 1, name: 'Ann' };
I need to access a property of that object dynamically, for example:
xxxxxxxxxx
1
function setter(object, property, value) {
2
object[property] = value;
3
}
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.
xxxxxxxxxx
1
var hasOwnProperty = Object.prototype.hasOwnProperty;
2
3
function setProperty(object, key, value) {
4
var tmp = key.toLowerCase();
5
for (var item in object) {
6
if (hasOwnProperty.call(object, item) && tmp === item.toLowerCase()) {
7
object[item] = value;
8
return;
9
}
10
}
11
}
12
13
14
// Usage example:
15
16
var myObject = { id: 1, name: 'Ann' };
17
18
setProperty(myObject, 'ID', 2);
19
20
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 commentsShow commentsAdd comment