javascriptjsonbetfair

use indexOf when accessing JSON with Javascript


can I use indexOf when looping through parsed Json output to find a particular object if only given a partial amount of it's identifier.

Basically I am calling the Betfair API to get the selectionIds but sometimes I only have the surname of a player and not the full name how is provided by the json response. I think I need something like this but cannot figure it out. The Json data is

var response = { jsonrpc: '2.0',
  result: 
   [ { marketId: '1.118739296',
       marketName: 'Match Odds',
       marketStartTime: '2015-05-13T01:00:00.000Z',
       totalMatched: 17,
       runners: 
    [ { selectionId: 7750118,
        runnerName: 'Makoto Ninomiya',
        handicap: 0,
        sortPriority: 1,
        metadata: { runnerId: '7750118' } },
      { selectionId: 7659425,
        runnerName: 'Su Jeong Jang',
        handicap: 0,
        sortPriority: 2,
        metadata: { runnerId: '7659425' } } ],
       eventType: { id: '2', name: 'Tennis' },
       competition: { id: '7354189', name: 'ITF Women Kurume 2015' },
       event: 
    { id: '27442711',
      name: 'Ninomiya v Jang',
      countryCode: 'JP',
      timezone: 'Japan',
      openDate: '2015-05-13T01:00:00.000Z' } } ],
  id: 1 }

code is

for (var i = 0; i<= Object.keys(response.result).length; i++ ) {
    if(response.result[0].runners[i].runnerName == 'Su Jeong Jang'){
      document.body.innerHTML = response.result[0].runners[i].selectionId;
    }      
 }

This finds the selectionID fine, but if I use only the surname like this I don't get a match

 for (var i = 0; i<= Object.keys(response.result).length; i++ ) {
        if(response.result[0].runners[i].runnerName.indexOf('Su Jeong') >0 {
          document.body.innerHTML = response.result[0].runners[i].selectionId;
        }      
     }

Can anybody point me in the right direction? Many thanks.


Solution

  • Your problem is that you are using > 0. However, indexOf will find the surname that you use in the first position, and return 0. Use > -1 or >= 0 instead.