How to tell if a property exists in a JSON object
Posted on : 12-07-2009 | By : chelfers | In : Javascript, Web
0
I usually don't claim to be an expert in anything, but that really depends on who I am talking to at the time. In my never ending crawl across the web trying to pick up the latest in web development I often come across blog posts or comments questioning how to tell if a property is set or not in a JSON object.
I'm not sure if the way I handle this is the best way, but it works for me and hopefully it will for you too. For this example I will simply make a function call and alert the result if it exists.
In this function call we are passing a simple JSON object with the 'question' property equal to 'can you hear me?'. Below is the function to alert our message and test if our properties are set.
function Dialog( setOptions ) { setOptions = { question : ( 'question' in setOptions ) ? setOptions.question : null, answer : ( 'answer' in setOptions ) ? setOptions.answer : 'No, type louder' }; if ( setOptions.question != null ) { alert( setOptions.answer ); } }
The important part to pay attention to is the in statement. The bread-n-butta of this whole guy is 'question' in setOptions, or in other words, is the 'question' property residing in the setOptions object?
If the 'question' property is indeed passed we should get our defaulted answer. If we passed the 'answer' property initially with our 'question' property we could have set our own answer just like we did for the question answering our own question.
I'm sure there are many different ways of doing this, but like I said it works for me and so far I haven't required an alternative on any project I have worked on so far.
Keep your heads down and fingers flying!



