How to use the ternary operator to determine what to display?

1

How can I properly use the Ternary Operator in JavaScript. I have the following code:

var Requisitar = function(){
    setTimeout(function(){
        $.ajax({
        url: 'https://steamgaug.es/api/v2', // Acesso direto a API
        success: function(resposta){ // <-- variavel resposta vem com todos dados da API
            // Steam Loja Comunidade
            $("#dota2-statusapidota").html(resposta["IEconItems"]["570"]["online"]);
        }
        });
    Requisitar();
    },5000);//1000=a um segundo, altere conforme o necessario
};
Requisitar();//Dispara

So when used in HTML:

li id="dota2-statusapidota" < /li >

The value shown is 1.

How can I use the ternary operator correctly so that this "1" is displayed as "Online"?

JSON Received:

{
    "ISteamClient": {
        "online": 1
    },
    "SteamCommunity": {
        "online": 1,
        "time": 25,
        "error": "No Error"
    },
    "SteamStore": {
        "online": 1,
        "time": 2,
        "error": "No Error"
    },
    "ISteamUser": {
        "online": 1,
        "time": 20,
        "error": "No Error"
    },
    "IEconItems": {
        "440": {
            "online": 1,
            "time": 27,
            "error": "No Error"
        },
        "570": {
            "online": 1,
            "time": 27,
            "error": "No Error"
        },
        "730": {
            "online": 1,
            "time": 27,
            "error": "No Error"
        }
    },
    "ISteamGameCoordinator": {
        "440": {
            "online": 1,
            "schema": "http://media.steampowered.com/apps/440/scripts/items/items_game.b7f5e5dded37fbd6494d96690a71e507d28279f7.txt",
            "error": "No Error",
            "stats": {
                "spyScore": "0",
                "engiScore": "0"
            }
        },
        "570": {
            "online": 1,
            "error": "No Error",
            "stats": {
                "players_searching": 20509
            }
        },
        "730": {
            "online": 1,
            "error": "No Error",
            "stats": {
                "players_searching": 2310,
                "players_online": 111128
            }
        }
    }
}
    
asked by anonymous 20.02.2015 / 21:46

1 answer

4

So:

var online = resposta["IEconItems"]["570"]["online"];
$("#dota2-statusapidota").html(online === 1 ? "online" : "offline");

I put the original data in a variable for easy reading. The use of the operator is simple: if online is 1 , the expression returns the string "online" , otherwise it returns "offline" .

A ? B : C;
    ^   ^
    |   retornado se A não for verdadeiro
    |
    retornado se A for verdadeiro
    
20.02.2015 / 21:49