3

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)?

Qualsiasi
  • 51
  • 2
  • 6
  • You can use a reducer, see here http://stackoverflow.com/questions/18891939/javascript-retrieve-object-property-path/18892019#18892019, and MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce – elclanrs Oct 20 '14 at 09:10
  • @elclanrs reduce() belongs to Array. Also, the items in array are known in reduce(). But in Qualsiasi's case properties may/may not be there – Thaadikkaaran Oct 20 '14 at 09:30
  • 1
    `['a','b','c'].reduce(function(o,x){return o&&o[x]},obj)` – elclanrs Oct 20 '14 at 09:37
  • @elclanrs It's robust but I don't think it's compact nor easy to read, maybe enriching Object prototype with a getter based on this reducer might be a good choice. Anyway I was hoping some implementation that wouldn't require a major code rewrite. – Qualsiasi Oct 20 '14 at 09:47
  • Is there still no succinct easy to understand solution that does not require the reduce function? If not I will be writing an npm module for this. Looking for an easy solution in some of my own code too. – Dawson B Apr 23 '16 at 05:17

0 Answers0