Sartheris Stormhammer Sartheris Stormhammer - 1 year ago 70
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


enter image description here

if I do it like this

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

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 Source

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"]) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download