Languages

JavaScript - access property case-insensitively

0 points
Asked by:
Jan-Alfaro
681

How can I specify an object's property by name regardless of case?

Let's say I have an object:

I need to access a property of that object dynamically, for example:

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
Answered by:
Admin Dirask Community
4380

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.

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

  1. JavaScript - convert string to lowercase

  2. JavaScript - case insensitive string comparison

References

  1. String.prototype.toLowerCase() - JavaScript | MDN
0 commentsAdd comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join