Categories
JavaScript Answers

How to access JavaScript property case-insensitively?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *