Home > Net >  Checking if any values in object are not null
Checking if any values in object are not null

Time:10-25

I have the following code:

err = {
  "content-type": null,
  phone: null,
  firstName: null,
  lastName: null,
  email: null,
  website: null,
  supplier: null
}

console.log(Object.keys(err).some(key => key !== null))

I learnt about the .some function from stackoverflow, but this is returning true. All the values are null, so I would expect it to return false.

I just need a way to check if any of the values are not null, then I know there are errors in the form.

CodePudding user response:

Use the Object.values() method to get an array of the object's values. Use the Array.every() method to iterate over the array. Check if each value is equal to null. The every() method will return true if all values are null.

const err = {
  "content-type": null,
  phone: null,
  firstName: null,
  lastName: null,
  email: null,
  website: null,
  supplier: null
}

const result = Object.values(err).every(value => {
  if (value === null) {
    return true;
  }

  return false;
});

console.log(result);

Reference

  • Related