Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

node.js - Access Javascript nested objects safely

I have json based data structure with objects containing nested objects. In order to access a particular data element I have been chaining references to object properties together. For example:

var a = b.c.d;

If b or b.c is undefined, this will fail with an error. However, I want to get a value if it exists otherwise just undefined. What is the best way to do this without having to check that every value in the chain exists?

I would like to keep this method as general as possible so I don't have to add huge numbers of helper methods like:

var a = b.getD();

or

var a = helpers.getDFromB(b);

I also want to try to avoid try/catch constructs as this isn't an error so using try/catch seems misplaced. Is that reasonable?

Any ideas?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Standard approach:

var a = b && b.c && b.c.d && b.c.d.e;

is quite fast but not too elegant (especially with longer property names).

Using functions to traverse JavaScipt object properties is neither efficient nor elegant.

Try this instead:

try { var a = b.c.d.e; } catch(e){}

in case you are certain that a was not previously used or

try { var a = b.c.d.e; } catch(e){ a = undefined; }

in case you may have assigned it before.

This is probably even faster that the first option.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...