Sometimes, we want to access JavaScript property case-insensitively.
In this article, we’ll look at how to access JavaScript property case-insensitively.
How to access JavaScript property case-insensitively?
To access JavaScript property case-insensitively, we can use the Object.keys method to get an array of keys.
And then we use the array find method to find the key.
For instance, we write
const myObject = { mIxeDCaSEKeY: "value" };
const searchKey = "mixedCaseKey";
const asLowercase = searchKey.toLowerCase();
const k = Object.keys(myObject).find(
(key) => key.toLowerCase() === asLowercase
);
const val = myObject[k];
to call Object.keys with myObject to get an array of keys from myObject.
Then we call find with a callback that converts key to lower case with toLowerCase.
And we compare that with asLowercase to find the key k.
Next, we get the val with myObject[key].
Conclusion
To access JavaScript property case-insensitively, we can use the Object.keys method to get an array of keys.
And then we use the array find method to find the key.