Accessing JavaScript Properties in Safe Mode
Suppose you are receiving JSON data from a legacy system that sends objects that may or may not have any properties, which in turn may or may not be nested very deeply into the object. I think that sooner or later everyone faced this 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 access properties in a safe way, I often refer to them as:
> jsonResponse.a && jsonResponse.a.b && jsonResponse.a.b.c
undefined
> ((jsonResponse.a||{}).b||{}).c
undefined
What I'm asking is a compact, easy-to-read, fast way to write, a safe way to access deep properties when they exist and return undefined
when they don't.
What would you suggest? Is there a way to create an object that returns undefined
even for (undefined).property
(I read about get
or defineGetter
, but they don't seem flexible enough - and they are not supported in older browsers)
source to share
No one has answered this question yet
See similar questions:
or similar: