What is the most elegant way of checking if multiple objects exist, in Node.js?

37 Views Asked by At

Suppose I have several environment variables, going by the hypothetical names OBJECT_A, OBJECT_B, OBJECT_C, etc. I must implement a function doTheyExist() that must return a boolean. I want to know what is the cleanest (as in, as little code as possible and as easy to read as possible) and the most efficient (as in using as few resources as possible) to implement such a function.

function doTheyExist() {
    if (
        process.env.OBJECT_A &&
        process.env.OBJECT_B &&
        process.env.OBJECT_C &&
        ...
    ) return true;
    return false;
}

I initially thought I could just use a return (object_a && object_b && ...); would be the way to go, as it saves a line, but turns out it might return an undefined, rather than a false. I cannot have that. The return must be strictly true or false. Is there any cleaner way of doing this? And I know this is a minor thing and won't affect overall performance even if I were to check for thousands of variables, but is this the most efficient way of making checks like these?

1

There are 1 best solutions below

0
0stone0 On

You could define an array of keys you want to check, then using every() you can check if the object hasOwnProperty for all the keys.

const data = {
    OBJECT_A: 1,
    OBJECT_B: 2,
    OBJECT_C: 3
};

const objectHasKeys = (obj, keys) => keys.every(k => data.hasOwnProperty(k));

console.log(objectHasKeys(data, [ 'OBJECT_A' ]));
console.log(objectHasKeys(data, [ 'OBJECT_A', 'OBJECT_B' ]));
console.log(objectHasKeys(data, [ 'OBJECT_X', 'OBJECT_Y' ]));