Languages

JavaScript - access property case-insensitively

0 points
Asked by:
Jan-Alfaro
711

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
Answered by:
Jan-Alfaro
711

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

  1. JavaScript - convert string to lowercase

  2. JavaScript - case insensitive string comparison

References

  1. String.prototype.toLowerCase() - JavaScript | MDN
0 comments Add 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