2

I have dictionary object dictionary withing TypeScript which is storing values in the following fashion:

{
  "abc": {
    "country": "Germany",
    "population": 83623528
  },
  "CDE": {
    "country": "Austria",
    "population": 8975552
  },
  "efg": {
    "country": "Switzerland",
    "population": 8616571
  }
}

I have another array tabledata which is storing values of keys as Name but the case for Name can be different within array.

Now, I am trying to search for values within dictionary using the following statement:

hostDictionary[tableData[i].Name]

It works fine when the case matches between tableData[i].Name and dictionary key

But I am getting null value when the case doesn't match.

For example,

hostDictionary[tableData[i].Name] is returning null when tableData[i].Name = "cde"

meallhour
  • 13,921
  • 21
  • 60
  • 117
  • 1
    Does this answer your question? https://stackoverflow.com/questions/12484386/access-javascript-property-case-insensitively – sujeet Apr 23 '20 at 18:05
  • Why not use always-lowercase property names in your object? – Bergi Apr 23 '20 at 18:48

3 Answers3

0

You have to iterate over its keys to compare .

Keys are case-senstitive, comparing them after converting lower or upper case will cause inconsistency in your search.

If you want to get the value without minding case.

function getKey(key, obj) {
   return Object.keys(obj).find((el) => el.toLowerCase() === key.toLowerCase()) ? obj[el]: null;
}
sujeet
  • 3,480
  • 3
  • 28
  • 60
0

It will not be as efficient as a dictionary but this might work.

function get(key){ 
   for(let prop in hostDictionary){
     if( prop.toLowerCase() == key.toLowerCase())
        return hostDictionary[prop];
     }
}
Redet Getachew
  • 120
  • 1
  • 8
-2

Just use toUppercase on each side of the comparison https://www.w3schools.com/jsref/jsref_touppercase.asp

const A = 'Asdf'
const B = 'asdf'

A === B // false
A.toUpperCase() === B.toUpperCase() // true
Odinn
  • 808
  • 5
  • 23