0
window.addEventListener('keydown', (e) => {
    let arrowsObj = {
        "ArrowUp": 1,
        "ArrowDown": 2,
        "ArrowLeft": 3,
        "ArrowRight": 4
    }
    let eventKey = e.key;
    console.log(arrowsObj.eventKey);
});

The above code doesn't work, so I did the following checks:

arrowsObj.hasOwnProperty(eventKey)

if(eventKey in arrowsObj)

Both returning true, what have I missed? Would that be because of data type?

Thanks!

void
  • 36,090
  • 8
  • 62
  • 107
Kenny
  • 153
  • 1
  • 1
  • 9

2 Answers2

2

In your case, you can not use .dot notation to access the value from the object as it is not a string key it is a variable storing the key.

Use Bracket notation instead arrowsObj[eventKey]

I would still suggest you to use .hasOwnProperty otherwise if you will press key other than arrow keys then you will get undefined in your console.

window.addEventListener('keydown', (e) => {
    let arrowsObj = {
        "ArrowUp": 1,
        "ArrowDown": 2,
        "ArrowLeft": 3,
        "ArrowRight": 4
    }
    let eventKey = e.key;
    console.log(arrowsObj[eventKey]);
});
void
  • 36,090
  • 8
  • 62
  • 107
  • thank you void, just tested with your solution and it works :), but I am still thinking of what you said about "it is not a string key it is a variable storing the key". Because when I define a dummy obj in the console and use obj.key, this works, while obj[key] doesn't, but will do further searching about this. Thanks again! – Kenny Mar 02 '18 at 12:37
  • 1
    @Kenny in the case you have mentioned `obj["key"]` should work. While using dot notation say a.b, b should be a key present in a and when using bracket notation a[b] or a["b"], b is a variable storing some other string and in the later case b is the string. Hope this clears your doubt. And do mark the answer correct :) – void Mar 02 '18 at 12:40
  • Thanks again void, so the point is the type of the 'key', and now I am thinking of some json stuff, the keys are wrapped inside double quotes, but those are not var, so dot notation works, while [] doesn't – Kenny Mar 02 '18 at 12:50
  • @Kenny no I guess you are still a bit confused.. Why dont you read https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets – void Mar 02 '18 at 12:52
1

Use bracket notation console.log(arrowsObj[eventKey]); intead dot

Arkej
  • 2,221
  • 1
  • 14
  • 21