views:

86

answers:

2

Im using an ajax json response to build some html to place in a webpage. Occasionally I'll come across an empty value in my json. This results in an empty object being placed into the html.

I would prefer not to check that each value is not an object, as that doesn't seem efficient. Is there a better way? my code works like this

var firstVar=jsonObj.fristVar;
var secVar=jsonObj.secVar;
var thirdVar=jsonObj.thirdVar;
var fourthVar=jsonObj.fourthVar;
...
var htmlResponse='<div class="'+firstVar+'">'+secVar+'<span class="'+thirdVar+'">'+fourthVar+'</span>...';
jQuery("body").html(htmlResponse);
+2  A: 

If you want to specify default values when they are null, you can just do this:

var firstVar = jsonObj.firstVar || '';
var secVar = jsonObj.secVar || 'No Value';
...

Unrelated to your question, have you looked at an implementation of jQuery templating?

Chetan Sastry
That will set the *default* value not only when the members are `null`, also when they are `0`, `false`, `undefined`, empty string and `NaN`.
CMS
Yes, Caveat emptor!
Chetan Sastry
The code you've written above makes sense, and it should work, but I'm still getting the response of "[object object]" when using var firstVar=jsonObj.firstVar || ''; - When I alert(firstVar.toSource), I get ({}). Any idea why I'm still getting this?
pedalpete
also, I wasn't familiar with jQuery templating before, and I'm not really sure why it is beneficial, but I'll dig into it deeper. Thanks for expanding my knowledge.
pedalpete
A: 

You could use a tertiary operator:

var firstVar = (jsonObj.fristVar != null) ? jsonObj.fristVar : "some default value";
Kaleb Brasee