Javascript 如何使字典搜索在Typescript中不区分大小写?
我有dictionary objectJavascript 如何使字典搜索在Typescript中不区分大小写?,javascript,typescript,dictionary,ecmascript-6,Javascript,Typescript,Dictionary,Ecmascript 6,我有dictionary objectdictionary,它使用TypeScript以以下方式存储值: { "abc": { "country": "Germany", "population": 83623528 }, "CDE": { "country": "Austria", "population": 8975552 }, "efg": { "country": "Switzerland", "population":
dictionary
,它使用TypeScript以以下方式存储值:
{
"abc": {
"country": "Germany",
"population": 83623528
},
"CDE": {
"country": "Austria",
"population": 8975552
},
"efg": {
"country": "Switzerland",
"population": 8616571
}
}
我有另一个数组tabledata
,它将键的值存储为Name
,但是Name
的情况在数组中可能不同
现在,我尝试使用以下语句在字典中搜索值:
hostDictionary[tableData[i].Name]
当大小写在tableData[i].Name
和字典键
但当案例不匹配时,我得到的是空值
比如说,
hostDictionary[tableData[i].Name]
在tableData[i].Name=“cde”进行比较时返回null
您必须迭代其键才能进行比较。
键是区分大小写的,在转换为低位或低位后进行比较
大写将导致搜索不一致
如果您想在不考虑大小写的情况下获取值。
function getKey(key, obj) {
return Object.keys(obj).find((el) => el.toLowerCase() === key.toLowerCase()) ? obj[el]: null;
}
它的效率不如字典,但这可能会奏效
function get(key){
for(let prop in hostDictionary){
if( prop.toLowerCase() == key.toLowerCase())
return hostDictionary[prop];
}
}
这回答了你的问题吗?为什么不在对象中始终使用小写属性名?
function get(key){
for(let prop in hostDictionary){
if( prop.toLowerCase() == key.toLowerCase())
return hostDictionary[prop];
}
}