0

In JavaScript (or TypeScript), if I'm going to reference something like:

return myObj1.myObj2.myObj3.myProperty;

to be safe, I guard it with something like:

if (myObj1 && myObj2 && myObj3) 
    return myObj1.myObj2.myObj3.myProperty;
else
    return null;

Is there a more concise way of just getting null from the above reference without surrounding it by an if?

Please note, since I'll be using this in a TypeScript app, some solutions may not work with dynamic object definition.

Thanks.

Michael Witt
  • 1,582
  • 4
  • 22
  • 43
  • 1
    I suppose you mean `if (myObj1 && myObj1.myObj2 && myObj1.myObj2.myObj3)`? – Constantin Groß Oct 27 '17 at 15:01
  • [Accessing nested JavaScript objects with string key](https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key) – Andreas Oct 27 '17 at 15:03
  • What if you recursively prints the object is this what you need http://jsbin.com/xuniluqaqa/edit?js,console,output ? – xsami Oct 27 '17 at 15:12
  • @Andreas, your link provided a good answer at https://stackoverflow.com/a/6491509/1775513. Add as answer and I'll mark it as such. BTW, any idea if there is a performance degradation accessing a property like this? – Michael Witt Oct 27 '17 at 15:25

2 Answers2

1

You can define some temporary objects to substitute when a lookup fails.

return (((myObj1||{}).myObj2||{}).myObj3||{}).myProperty || null;

You can make a reusable object if desired.

const o = Object.create(null);

Then use it as needed.

return (((myObj1||o).myObj2||o).myObj3||o).myProperty || null;
llama
  • 2,535
  • 12
  • 11
  • Looks like a good Javascript solution. I didn't take into account that I might need a Typescript only solution because this gives errors because myObj2 does not exist on o (or {}). – Michael Witt Oct 27 '17 at 15:13
1

I'd use a library like lodash for this:

 //gets undefined if any part of the path doesn't resolve.
 const answer = _.get(myObj1, "myObj2.myObj3.myProperty");

 //gets null if any part of the path doesn't resolve.
 const answer2 = _.get(myObj1, "myObj2.myObj3.myProperty", null);

See https://lodash.com/docs/4.17.4#get for details.

Duncan Thacker
  • 5,073
  • 1
  • 10
  • 20