Locate id within json array[]

Asked

Viewed 999 times

1

Good night!

I’m having a problem locating array by square bracket case.

I’m trying to get the data from "Stats". But its only reference is "accountId" or "summonerName". To get the reference of "Stats" need to get the id "participantId" that’s inside the "participantIdentities".

But my problem is I’m not getting the id "participantId".

JSON Base - Example

{  
   "gameId":1189987226,
   "participantIdentities":[  
      {  
         "player":{  
            "summonerName":"Khal Droggo",
            "accountId":1595535
         },
         "participantId":1
      },
      {  
         "player":{  
            "summonerName":"Lefetos",
            "accountId":211703728
         },
         "participantId":2
      }
   ],
   "participants":[  
      {  
         "stats":{  
            "champLevel":16,
            "participantId":1
         },
         "participantId":1
      },
      {  
         "stats":{  
            "champLevel":15,
            "participantId":2
         },
         "participantId":2
      }
   ]
}

I’m using javascript language.

function callback(andress, fn){
    $.ajax({
        url: andress,
        type: 'GET',
        dataType: 'json',
        error: function(){},
        success: fn
    });
}

function stats(accountId){
    callback('https://api.myjson.com/bins/1ew27p', function(retorno) {
        var obj = retorno.participantIdentities;
        Object.keys(obj).forEach(function(prop) {
            if (obj[prop].accountId == accountId) {
                document.write(obj[prop].participantId);
            }
        });
    });
}

stats(211703728);

2 answers

0

Based on the answer to a question put to the Soen

The best solution is to use the method grep of jQuery.

var participante = $.grep( obj, function( n, i ) {
    return n.player.accountId===accountId;
});

To recover the value of participantId

participante[0].participantId

Getting your code like this.

function callback(andress, fn){
    $.ajax({
        url: andress,
        type: 'GET',
        dataType: 'json',
        error: function(){},
        success: fn
    });
}

function stats(accountId){
    callback('https://api.myjson.com/bins/1ew27p', function(retorno) {
      var obj = retorno.participantIdentities;
      var participante = $.grep( obj, function( n, i ) {
        return n.player.accountId===accountId;
      });
      console.log(participante[0].participantId);
    });
}

stats(211703728);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  • Instead of using foreach should I wear grep. Thank you very much guy, solved my problem!.

  • A very simple question, how to recover the value within the "player" participante[0].summonerName?

  • participante[0].player.summonerName

  • A doubt if there is no accountId in the JSON base, it will occur an error, how to treat this?

0


The logic you’re using to find the player works, only access to the field accountId is that it is not correct, this obj[prop].accountId.

Makes a foreach in participantIdentities means that each object of that foreach will be something like:

{  
     "player":{  
        "summonerName":"Khal Droggo",
        "accountId":1595535
     },
     "participantId":1
}

Which means to access the accountId will have to do .player.accountId instead of .accountId directly as you have.

So just change the if that has to:

if (obj[prop].player.accountId == accountId) { //agora .player.accountId

If player may not exist then it is appropriate to confirm whether it exists using the function hasOwnProperty what would turn out like this:

if (obj[prop].hasOwnProperty("player") && obj[prop].player.accountId == accountId) {

Example:

function callback(andress, fn){
    $.ajax({
        url: andress,
        type: 'GET',
        dataType: 'json',
        error: function(){},
        success: fn
    });
}

function stats(accountId){
    callback('https://api.myjson.com/bins/1ew27p', function(retorno) {
        var obj = retorno.participantIdentities;
        Object.keys(obj).forEach(function(prop) {
            if (obj[prop].hasOwnProperty("player") && obj[prop].player.accountId == accountId) { //if alterado aqui
                console.log(`Achou jogador ${obj[prop].player.summonerName} com participantId de ${obj[prop].participantId}`);
                return;//se achou não ve mais nenhum
            }
        });
    });
}

stats(211703728);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  • Your solution is also great. But there is a problem, in the JSON database there may be no array "accountId". In other words this will occur an error like Uncaught TypeError: Cannot read property 'accountId' of undefined.

  • @Augustojunior qual array ? o participantIdentities ? Put an example of the returned json in the answer when there is no array you are indicating, so I can give you a solution. Because from the error you’re showing it looks like every object in the participantIdentities may not have the field player defined.

  • I’ll explain how the json base works, inside the participantIdentities there may be several player and may simply not exist player. That is, if it doesn’t exist player error in this command if (obj[prop].player.accountId == accountId) because there is no accountId. When json base does not exist accountId would be so. https://jsfiddle.net/thLqyn4g/1/

  • @Augustojunior See if it exists is easy just use hasOwnProperty. But if there are several, it looks like ? it looks like an array of players ? Give a json example of when there are several. I’ve already updated the answer to hasOwnProperty

  • I put two examples as json can work. Several player https://jsfiddle.net/zvadty2t/ and without player https://jsfiddle.net/d55ymadL/

  • @Augustojunior according to these examples my edition will already work. I ask you to confirm if there is any case that is not working

  • Thanks a lot! With this function hasOwnProperty worked perfectly!

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.