有没有一种有效的方法来执行不区分大小写的 JavaScript 对象属性名称查找

Is there an efficient way to do a case-insensitive JavaScript object property name lookup?

本文关键字:JavaScript 大小写 对象 属性 查找 不区 一种 有没有 方法 有效 执行      更新时间:2023-09-26

我有一个特定的对象,其中属性的确切大小写事先并不知道。例如,属性名称可能是"AbC"或"Abc"或"abc"等。

但是,我知道只有一个存在。也就是说,我知道不能同时有属性"abC"和属性"abc"。

属性名称本身区分大小写。因此,如果它存储为 theObject.Abc 并且我查找 theObject.abc,我将找不到该属性。

在我的对象中可能有 1,000 个这样的属性。

如果每次我想进行查找时,我都会将要查找的属性的小写值与属性名称的小写值进行比较,这将是可能的,但效率低下,如下所示:

propertyName = inputValue.toLowerCase();
for (var i in theObject) {
   if (propertyName == i.toLowerCase()); // found a matching property name
}

有谁知道更聪明的方法吗?

由于解释需要很长时间的原因,我不能只是重新创建对象并使所有属性小写。我确实意识到如果可能的话,我可以找到

theObject['inputValue'.toLowerCase()]

径直。但正如我所说,我不能。对象中的属性名称是它们本来的样子,不能更改。问我为什么会离眼前的问题一个巨大的题外话。请相信我的话,对象被它拥有的属性名称所困。

有没有人知道在这种情况下进行不区分大小写的属性名称查找的有效方法?

甚至比西格弗里德走得更远:

var theObject = {aBc: 1, BBA: 2, CCCa: 4, Dba: 3};
var lcKeys = Object.keys (theObject).reduce (
                          function (keys, k) { keys[k.toLowerCase()] = k; 
                                               return keys }, {});
function getValue (key) { return theObject[lcKeys[key.toLowerCase ()]] }
console.log (getValue ('abc'));
console.log (getValue ('Dba'));

以Jelly的例子为基础,但可能更有效或更容易理解:

 var theObject = {aBc: 1, BBA: 2, CCCa: 4, Dba: 3};
 var theKeys = Object.getOwnPropertyNames(theObject);
 var lookup = {};
 theKeys.forEach(function(key) {
     lookup[key.toLowerCase()] = key;
 });
 var getPropValue = function(prop){
     return lookup[prop.toLowerCase()];
 }
 console.log(getPropValue('abc'))
 console.log(getPropValue('Dba'))

正如你所说,我认为你不想循环 Object 的方式。对于您的意见,我想到一种方法,更有效,更容易,并且它不会循环任何东西。

让我们看看小提琴:

https://fiddle.jshell.net/skgkLnx9/

下面是示例:

var theObject = {aBc: 1, BBA: 2, CCCa: 4, Dba: 3};
// if your env is < ES5, you can use a polyfill( like underscore or lodash provided `_.keys` method )
var theKeys = Object.getOwnPropertyNames(theObject).toString();
// or var theKeys = Object.keys(theObject);
var getPropValue = function(prop){
    var match = new RegExp(prop, 'i').exec(theKeys);
  return match && match.length > 0 ? theObject[match[0]] : '';
}
console.log(getPropValue('abc'))
console.log(getPropValue('Dba'))

我也了解您对您拥有的大数据的看法。我还使用我的代码来测试具有 500 个属性的对象,它可以直接返回。虽然当它非常非常大时,它可能有一些内存问题,但我认为这可以让你了解解决这个问题。

希望能帮助你:)