Search code examples
javascriptjsonsteamsteam-web-api

How do I console.log json information?


quite new to working with both api's and javascript. I'm trying to console.log out the amount of times a friend of mine has died in rust, but all items are named "name:" An img of what I mean:

enter image description here

I'm using axios to call the api, here's the code:

var statsApi = 'http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?';
var statsAppId = 'appid='+252490+'&'
var statsSteamApiKey = 'key='+process.env.STEAM_API+'&';
var statsUserArg = 'steamid='+userID; 
                
var steamStatsApi = statsApi + statsAppId + statsSteamApiKey + statsUserArg;

axios
  .get(steamStatsApi)
  .then((res) =>{
      message.channel.send("AAAA");
      // console.log(res['data']['playerstats']['stats']['name' == 'deaths']);
      for(re in res['data']['playerstats']['stats']) {
          if(re['name'] === 'deaths') {
              console.log('test');
              console.log(re['value']);
          }
          else {
              console.log('Fel');
          }
      }
  })
.catch((err) => {
    console.error('Error:', err);
}) 

Again if anyone knows how to get the amount of 'deaths' I'd be super grateful.


Solution

  • Turns out it was quite easy, if anyone has this problem just use the following code which I am about to provide:

    var index = -1;
    for(var i = 0; i < Object.keys(res['data']['playerstats']['stats']).length; i++) {
       if(res['data']['playerstats']['stats'][i]['name'] === 'deaths') {
          index = i;
          var userDeaths = res['data']['playerstats']['stats'][index]['value'];
          break;
       }
    }
    

    What this does is that it loops trough every object named "name:" until it finds 'deaths' in one of them. I change i to that and now i'm able to print out the value which i'm looking for.