Look up nested arrays of objects for a match by separate criteria on each level

Viewed 61

I want to loop type array to check if "facility" code is MA , then loop to exercise array to find if gym is in Greenville then return the greenville gym id using nested map function

let id == "No Data";
$.each(dietType, function (count, value) {
    var facCode = value.type.facility;
    if (facCode == "MA") {
                                                    
        if (id == "No Data") {
            var facilityArray = value.exercise;
            $.each(facilityArray, function (index, idObj) {
                if (idObj.gym == "Greenville") {
                    gymId = idObj.id;
                }
            });
        }
    }
}
JSON :
    {
    "physicals": {
        "followups": {
            "type": [{
                "facility": {
                    "desc": "Open daily",
                    "code": "MA"
                },
                "exercise": [{
                        "gym": "Shrewsburry",
                        "id": "1234"
                    },
                    {
                        "gym": "greensville",
                        "id": "4321"
                    }
                ],
                "regular": "N",
                "yoga": "true"
            }]
        }
    }
}

enter code here
2 Answers

You may chain 2 Array.prototype.find()'s, like that:

const src = {"physicals":{"followups":{"type":[{"facility":{"desc":"Open daily","code":"MA"},"exercise":[{"gym":"Shrewsburry","id":"1234"},{"gym":"greensville","id":"4321"}],"regular":"N","yoga":"true"}]}}},

      result = src.physicals.followups.type
        .find(({facility:{code}}) => code == 'MA')
        ?.exercise
        .find(({gym}) => gym == 'greensville')
        ?.id
        
console.log(result)

Use a filter to get the id when gym matches Greenville

if (id == "No Data") {
    var facilityArray = value.exercise;
    var greenvilleId = facilityArray
        .filter((facility) => facility.gym === "Greenville").id
}
Related