-1

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.

ymdahi
  • 165
  • 9

2 Answers2

1

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,
  ...
}
guest271314
  • 1
  • 15
  • 104
  • 177
  • Thanks, this is probably the easiest solution to implement. A few months ago I didn't have to do it this way - if the key screenLogoUrl didn't exist in the JSON then it would be ignored when I tried to bring it in to an array. I'm using the approach you outlined to defined a default value to prevent an empty value. – ymdahi Nov 11 '16 at 18:49
  • 1
    You could also use `Object.keys(data).forEach(function(key) { ... })` – Gavin Nov 11 '16 at 18:54
0

You can use the or operator if you want to give a fallback when defining things that might be undefined.

var screenLogoImage = skinData['skinconfig'][0]['skin'].screenLogoImage || "";

In this case, if it is undefined (or false), it will be empty string instead of undefined.

I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116