0

I'm trying to check to see if something exists in an array, let's say the array arr is:

{"targeting":{
     "key1":"1",
     "key2":"2"},
 "session": "1234"
}

I want to check to see if arr.targeting.key1 exists so I do:

if (true === !!arr.targeting.key1)

This is true if it exists, but what if arr is empty? Then I get an error:

cannot read properties of undefined, reading 'key1'

What is the simplest way to check for the presence of arr.targeting.key1 that will just return false if arr.targeting or arr themselves are undefined?

pg.
  • 2,503
  • 4
  • 42
  • 67

1 Answers1

1

Use optional chaining.

if (arr?.targeting?.key1)
Unmitigated
  • 76,500
  • 11
  • 62
  • 80