ymdahi ymdahi - 21 days ago 9
Javascript Question

Parsing JSON, return empty instead of undefined

I'm hoping someone give provide some guidance on the below:

I am fetching JSON with something like this:

$.getJSON(jsonPath, function(returnedData){
...
});


The object returned will look something like this:

...
"skin": {
"elapsedTextColor": "#ffffff",
"autoHideControls": "false",
"autoplay": "false",
"muted": "false",
...
}


I make use of this data like this:

...
skin : {
screenLogoImage : skinData['skinconfig'][0]['skin'].screenLogoImage,
screenLogoUrl : skinData['skinconfig'][0]['skin'].screenLogoUrl,
...
},


When the value doesn't exist in the JSON, the set value is "undefined".

Is there a way to return an empty value if infact the value doesn't exist in the JSON?

For example, if in the JSON, screenLogoImage is not defined, how do I get

skinData['skinconfig'][0]['skin'].screenLogoImage


to return empty (so that the library that makes use of the configuration ignores it and uses the default value for that attribute)?

Any guidance is greatly appreciated.

Answer

You can use || OR operator

skin : {
  screenLogoImage : skinData['skinconfig'][0]['skin'].screenLogoImage || settings.screenLogoImage,
  screenLogoUrl : skinData['skinconfig'][0]['skin'].screenLogoUrl || settings.screenLogoUrl,
  ...
}

or for..in loop

var data = {... screenLogoImage: undefined};
var settings = {screenLogoImage:"/path/to/resource/"} 
for (var key in data) {
 if (data[key] === undefined) data[key] = settings[key]
}

skin : {
  screenLogoImage : skinData['skinconfig'][0]['skin'].screenLogoImage,
  screenLogoUrl : skinData['skinconfig'][0]['skin'].screenLogoUrl,
  ...
}
Comments