Search code examples
javascriptarraysjsonstringify

JS How to access specific array value based on another value


I am trying to stringify an array and get the specific value where another value equals EFHK_ATIS:

const atisData = JSON.parse(req.responseText);
document.getElementById("metar").innerHTML = JSON.stringify(atisData.atis[??].atis_code);

If I replace the questionmarks with a number, it obviously works, but it returns the atis_code of the wrong element, since the order changes all the time. How can I replace the question marks in order to navigate to the correct value where callsign equals "EFHK_ATIS"?

Here is a sample of the JSON file. I want the atis_code where callsign is EFHK_ATIS.

 "atis": [
    {
      "cid": xxx,
      "name": "Example Name",
      "callsign": "ZBAA_ATIS",
      "frequency": "199.998",
      "facility": 4,
      "rating": 2,
      "server": "SINGAPORE",
      "visual_range": 0,
      "atis_code": "F",
      "text_atis": [
        "ZBAA INFORMATION F, 1100 UTC , DEPARTURE RUNWAY 01,36R,36L,",
        "LANDING RUNWAY 01,36L, EXPECT ILS APPROACH, RUNWAY 01,36L, WIND",
        "360 DEGREES AT 6 M/S , CAVOK TEMPERATURE 14 DEG C , DEWPOINT -6",
        "DEG C , QNH 1030 HPA , ADVISE ON INITIAL CONTACT YOU HAVE",
        "INFORMATION F, AND CONFIRM YOU WILL IMPLEMENT RNAV PROCEDURES."
      ],
      "last_updated": "2021-10-15T11:43:52.3645031Z",
      "logon_time": "2021-10-15T11:30:24.328892Z"
    },
    {
      "cid": yyy,
      "name": "Name Example",
      "callsign": "EFHK_ATIS",
      "frequency": "135.070",
      "facility": 4,
      "rating": 4,
      "server": "GERMANY",
      "visual_range": 0,
      "atis_code": "W",
      "text_atis": [
        "THIS IS HELSINKI-VANTAA ARRIVAL AND DEPARTURE INFORMATION W",
        "AT TIME 1120 EXPECT ILS APPROACH ARRIVAL RUNWAY 15",
        "DEPARTURE RUNWAY 22R TRANSITION LEVEL 70",
        "HEAVY BIRD ACTIVITY IN VICINITY OF HELSINKI-VANTAA WIND 160",
        "DEGREES 15 KNOTS VISIBILITY 3000 METERS LIGHT RAIN BROKEN 700",
        "FEET TEMPERATURE 9 DEW POINT 9 QNH 994 BECOMING VISIBILITY 10",
        "KILOMETERS ADVISE ON INITIAL CONTACT YOU HAVE INFORMATION W"
      ],
      "last_updated": "2021-10-15T11:45:03.875018Z",
      "logon_time": "2021-10-15T11:30:27.9814385Z"
    },
...

Solution

  • Filter method is what you're looking for

    let atis_data = [
        {"callsign":"ZBAA_ATIS", "atis_code": "123"},
        {"callsign":"ABCD", "atis_code": "abcd"}
    ]
    let filtered = atis_data.filter(data => data["callsign"] == "ZBAA_ATIS")
    let result = filtered.map(data => data["atis_code"])
    console.log(result)