Sartheris Stormhammer Sartheris Stormhammer - 15 days ago 5
Javascript Question

How to check if an object has a specific key without try/catch

I am receiving this JSON from server, and I need to check if it contains the key

read.nores


enter image description here

if I do it like this

if (data[0]["read.nores"]) {
return;
}


it will crash because it does not contain that key.

How can I check if the key is there without a try/catch method, something like .has("read.nores")?

Answer

Reading an undefined key safely produces undefined, but reading a key from undefined will throw, so the problem will be specifically that data[0] doesn't exist, not that data[0]["read.nores"] doesn't exist.

To check for that, change it to:

if (data[0] && data[0]["read.nores"]) {
    return;
}