How can I search for an element in json by the first letter in its value? My code for some reason does not work.

{"airlines":[{"iata":"NM","name":"Mount Cook Airlines"}]} 

Code:

 var airlines; $.getJSON('/json/airlines.json', function(json){ airlines = json; }); for (var i = 0; i < airlines.length; i++) { if ((airlines[i].name).slice(0,1) == 'M') { //do smth } } 
  • You didn't forget to parse the json into the object? - br3t
  • @ br3t well, of course. Updated code. - JamesJGoodwin
  • It seems like getJSON does not send out variables, it is necessary to put a loop inside it. - greybutton
  • @greybutton everything he beautifully conveys. I use the same method on one page. - JamesJGoodwin
  • Probably, you have in variable airlines is not what you expect. Try airlines = json.airlines; - Dmitry

2 answers 2

 $.each(airlines, function(key, value){ if (key == 'M') { //do smth } }); 

    Understood. In the cycle you need to use the following construction:

     for (var i in airlines.airlines) { 
    • Normal for airlines.airlines should work too. - br3t