0

Let's say I have an object in which the value of each field is retrieved with an individual call:

let ExampleObj = {
  foo: getFoo(),
  bar: getBar(),
  baz: getBaz(),
  ...
} 

I have a function that will return the object if and only if all fields evaluate as non-null:

let returnsExampleObj = () => {
  // if (!!ExampleObj.foo && !!ExampleObj.bar && !!ExampleObj.baz) {
  //   return ExampleObj
  // } else {
  //   return undefined
  // }
}

I can obviously just manually check each field to see whether it's null or not like in the above example, but is there a more elegant way of doing this? There may be dozens of fields in this object and to check each one manually would be very tedious.

user7467314
  • 725
  • 1
  • 6
  • 10
  • When you say "evaluate as non-null", what do you mean? Do you mean truthy (see [here](https://stackoverflow.com/questions/5515310/is-there-a-standard-function-to-check-for-null-undefined-or-blank-variables-in))? – jarmod Mar 10 '21 at 01:05

1 Answers1

3

Just check that .every of the values are truthy:

const returnsExampleObj = () => {
  return Object.values(ExampleObj).every(Boolean) ? ExampleObj : undefined;
};
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Problematic with `{ intval: 0 }`? Not clear the OP wants int zero to be treated like null/undefined. Also empty string and NaN potentially problematic, depending on what the OP actually wants. – jarmod Mar 10 '21 at 01:04
  • He's using `!!`, which sounded like it's working for his purposes. Sure, if it's an issue, strictly compare against null instead. `.every(val => val !== null)` – CertainPerformance Mar 10 '21 at 01:05
  • Yup, unclear spec here - you will need to charge the OP another $2500 if the spec changes ;-) – jarmod Mar 10 '21 at 01:07