Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
772 views
in Technique[技术] by (71.8m points)

object - Access JavaScript property case-insensitively?

Assume I have an object:

var obj = {
  foo:"bar",
  fizz:"buzz"
};

I need to access a property of that object dynamically like so:

var objSetter = function(prop,val){
  obj[prop] = val;
}

No problems there, except for that prop needs to be case insensitive in case the property name is passed into the function as, say, Foo instead of foo.

So how can I point to an object's property by name without regard to case? I would like to avoid iterating the entire object if possible.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this:

var myObject = { "mIxeDCaSEKeY": "value" };

var searchKey = 'mixedCaseKey';
myObject[Object.keys(myObject).find(key => key.toLowerCase() === searchKey.toLowerCase())];

You can alternatively already provide the searchKey in lowercase.

If you want it as a function:

/**
  * @param {Object} object
  * @param {string} key
  * @return {any} value
 */
function getParameterCaseInsensitive(object, key) {
  return object[Object.keys(object)
    .find(k => k.toLowerCase() === key.toLowerCase())
  ];
}

If the object can't be found, then it'll return undefined, just like normal.

If you need to support older browsers, then you can use filter instead:

function getParameterCaseInsensitive(object, key) {
  return object[Object.keys(object).filter(function(k) {
    return k.toLowerCase() === key.toLowerCase();
  })[0]];
}

I suggest using the polyfills for Object.keys() and Array.filter() if you need even older support.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.7k users

...