0

first time dealing with json, so not really sure.. when a user online the api returns with

user example
live    true
viewers 22
passwordProtected   false
banned  false

but when im offline "viewers" gets removed. so data.viewers comes back as undefined, how can i change it to e.g offline?

script:

<script>
$.getJSON('https://example.com/api/example', function(data) {

    var text = `${data.viewers}`


    $(".mypanel").html(text);
});

</script> 
Vue
  • 1

2 Answers2

0

You can use the hasOwnProperty function.

var text = "offline";
if(data.hasOwnProperty('viewers'){
  text = data.viewers;
}
NoobishPro
  • 2,539
  • 1
  • 12
  • 23
0

You could check for undefined like so:

var text = "offline";
if (data.length && data.viewers !== undefined) {
    var text = data.viewers;
}

or with a ternary operator:

var text = (data.viewers !== undefined) ? data.viewers : "offline";

Ps. no need for the interpolation when saving a variable. ie `${data.viewers}` This is used when adding variables to a string value like html.

JeremyS
  • 427
  • 2
  • 7
  • The template literal may still be useful. It causes `data.viewers` to be coerced to a string and assign that to `text`. If `text` was `false`, `$(".mypanel").html(text);` would cause `$(".mypanel")` to be empty. A string would work normally. – Sebastian Simon Jun 12 '18 at 23:24
  • Coercing the data to a string this way is useful. Thanks for the tip, but I'm not sure sending `false` as a string to the browser is generally what is wanted here. Either way, the `||` statement from your comment above is the cleanest. – JeremyS Jun 13 '18 at 18:06