1

Possible Duplicate:
javascript test for existence of nested object key
In JavaScript, is there an easier way to check if a property of a property exists?

I've been searching for an elegant way to verify if the entire object path is defined.
For example: person.positions.values[0].company.name
On every step of the way, after the person, it can be undefined.
Can this be done without actually going through them one by one?


Thank you.

Community
  • 1
  • 1
thedp
  • 8,350
  • 16
  • 53
  • 95
  • 1
    The "proxy" feature proposed for next-generation JavaScript (probably) will make this possible (with a little work on the object definitions), but currently you're stuck with doing it yourself. – Pointy Oct 25 '12 at 23:01
  • 1
    CoffeeScript has a nice construct for this: person.positions?.values[0]?.company?.name – Matt Stone Oct 25 '12 at 23:04
  • ES2020 also allows the CoffeeScript style that Matt Stone mentions above. For example: `const exists = obj1?.obj2?.obj3` etc. Prefix each dot with a question-mark and if any of the sub-objects are not present, the entire chain will return undefined. – Matt van Andel Jan 25 '22 at 23:31

0 Answers0