Assume you're receiving JSON data from a legacy system which sends objects which may or may not have some properties which in turn may or may not be nested very deep in the object. I think everyone sooner or later faced this kind of problem:
> jsonResponse = JSON.parse('{"a": 1}')
Object {a: 1}
> jsonResponse.a
1
> jsonResponse.a.b
undefined
> jsonResponse.a.b.c
Uncaught TypeError: Cannot read property 'c' of undefined
Now, what you usually do is to access properties in a safe way, I often access them as:
> jsonResponse.a && jsonResponse.a.b && jsonResponse.a.b.c
undefined
> ((jsonResponse.a||{}).b||{}).c
undefined
What I'm asking for is a compact, easy to read, fast to write, safe way to access deep properties when they exists and return undefined
when they don't.
What would you suggest? Is there any way to build an object that returns undefined
even for (undefined).property
(I've read about get
or defineGetter
but they don't look flexible enough - and they're not supported on older browsers)?