Question

Working on a flight booking website. Have a json file which contains the airport codes, city name and country name.

[{"iata":"UTK","lon":"169.86667","iso":"MH","status":1,"name":"Utirik Airport","continent":"OC","type":"airport","lat":"11.233333","size":"small"}]

Now if my iata airport code matches to UTK i want to return the name.

Was it helpful?

Solution

Use filter() to find the object within the Array by its iata:

var arr = [{"iata":"UTK","lon":"169.86667","iso":"MH","status":1,"name":"Utirik Airport","continent":"OC","type":"airport","lat":"11.233333","size":"small"}];

function findByCode(arr, iata){
    var filtered = arr.filter(function(e){return e.iata = iata});
    return (filtered.length == 1) ? filtered[0]:undefined;
}

console.log(findByCode(arr,"UTK").name);

JS Fiddle: http://jsfiddle.net/dE9nP/

OTHER TIPS

$string = '[{"iata":"UTK","lon":"169.86667","iso":"MH","status":1,"name":"Utirik Airport","continent":"OC","type":"airport","lat":"11.233333","size":"small"}]';
 $data = json_decode($string);
echo count($data);
for($i=0;$i<count($data);$i++){
if($data[$i]->iata == 'UTK') echo $data[$i]->name;
}

you can use file_get_contents if the data in a file instead of $string;

This is basic searching! You need to loop over the array, and check each item for the matching code, then return the result. Here is a function:

function findAirport(myArray, iata){
    for(var i = 0; i < myArray.length; i++){
        var item = myArray[i];
        if(item["iata"] === iata){
            return item;
        }
    }
    return null;
}

You can use that function like so:

var airports = [{"iata":"UTK","lon":"169.86667","iso":"MH","status":1,"name":"Utirik Airport","continent":"OC","type":"airport","lat":"11.233333","size":"small"}];
var match = findAirport(airports, "UTK");
if(match){
    console.log("name = " + match.name);
}

Just to highlight my preference to using simple for loops over other functions such as filter, here is a performance test comparing my answer to the other one that uses filter. I know it's meaningless in most real use cases, but I wanted to keep a reference to the jsperf link :)

NOTE: This answer was provided before the question tags were edited. At the time of posting this question was asking for a javascript solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top