Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

Take an object like this

book.chapter.paragraph.sentence.word

assume you want to retrieve a certain word

book[6][3][15][3]

to be certain to reference an existing word, do you really have to perform a check like this...

if(typeof book[6] !== "undefined" && typeof book[6][3] !== "undefined" && typeof book [6][3][15] !== "undefined" && typeof book[6][3][15][3] !== "undefined") ...

...or is there a better way?

share|improve this question

Normally for dynamic access to nested properties you are expected to make an iterative check. However you might also use a try catch and parse the error message ugliness to access the undefined property. Such as

try{
var book = {page111: {paragraph2:{sentence4:{word12:"test"}}}};
    list = ["page112","paragraph2","sentence4","word12"],
    word = book[list[0]][list[1]][list[2]][list[3]];
    console.log(word);
}catch(e){console.log(list[list.indexOf(e.message.match(/\'(.*)\'/)[1])-1], "is undefined")}

I have to agree that it is very ugly.

share|improve this answer
    
You say that an iterative check is expected: this was, in fact, my first idea. I thought it would be an atrocious solution, but if it is the norm as you imply, I would go for that. I assumed there could be a built-in function for this kind of iterative check, that I was somehow missing... – resle 14 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.