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.

4

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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; 

1 Comment

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 {}).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.