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.

3
  • 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. Commented Oct 25, 2012 at 23:01
  • 1
    CoffeeScript has a nice construct for this: person.positions?.values[0]?.company?.name Commented Oct 25, 2012 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. Commented Jan 25, 2022 at 23:31

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.