Check the response of an API for correctness I expecting the response of an API to be a array of objects like this:

[
    {
        "code": "X",
        "name": "Product A",
        "pricings": []
    },
    {
        "code": "Y",
        "name": "Product B",
        "pricings": []
    },
    {
        "code": "Z",
        "name": "Product C",
        "pricings": []
    }
]


I want to check if the response actually looks like this, to sort out error's.

I did the following:

function checkResponseApi(response, mustHave) {     
    if(Array.isArray(response)) {

        if(response.length === 0) {
            return false;
        }

        var success = response.every(obj =&gt; {
            var keys = Object.keys(obj);
            var output = mustHave.map(el =&gt; keys.includes(el));

            return output.indexOf(false) === -1;
        })

        return success;
    } else {
        return false;
    }
}



if (checkResponseApi(arr, ["code", "name", "pricings"])) {
    // continue
} else {
    // handle error
}


Is this a valid solution? Maybe you can share some experience and provide another/better approach.

Thanks in advance.
Towards better performance and code organization

The list of required fields is better defined as const at top level:

const requiredFields = ["code", "name", "pricings"];


There are 2 negative outcomes that can be combined and checked at once:
1) if the response is not of Array type, 2) if it's empty array. The Consolidate conditional expression technique is applied.

if (!Array.isArray(resp) || !resp.length) {
    return false;
}


Instead of getting list of keys for each object in response array with var keys = Object.keys(obj) - the more efficient and faster way is to just apply obj.hasOwnProperty(el) to check if an object obj has required field el as a key.
All the rest "movements" in the initial approach are redundant and eliminated.



The final optimized approach:



function checkResponseApi(resp, mustHave) {     
    if (!Array.isArray(resp) || !resp.length) {
     return false;
    }
    return resp.every(obj =&gt; {
        return mustHave.every(el =&gt; obj.hasOwnProperty(el))
    });
}

let arr = [
    {"code": "X", "name": "Product A", "pricings": []},
    {"code": "Y", "name": "Product B", "pricings": []},
    {"code": "Z", "name": "Product C", "pricings": []}
];
const requiredFields = ["code", "name", "pricings"];


if (checkResponseApi(arr, requiredFields)) {
    console.log('Ok')
} else {
    console.log('Bad response')
}