1

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);
pedalpete
  • 21,076
  • 45
  • 128
  • 239

2 Answers2

2

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?

Community
  • 1
  • 1
Chetan S
  • 23,637
  • 2
  • 63
  • 78
  • 5
    That will set the *default* value not only when the members are `null`, also when they are `0`, `false`, `undefined`, empty string and `NaN`. – Christian C. Salvadó Dec 09 '09 at 23:54
  • 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 Dec 10 '09 at 19:50
  • 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 Dec 10 '09 at 19:51
1

You could use a tertiary operator:

var firstVar = (jsonObj.fristVar != null) ? jsonObj.fristVar : "some default value";
Kaleb Brasee
  • 51,193
  • 8
  • 108
  • 113