Richard Bridge
Richard Bridge

Reputation: 388

Checking if any values in object are not null

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.

Upvotes: 0

Views: 72

Answers (2)

Ben Aston
Ben Aston

Reputation: 55789

There is nothing wrong with using Array#some here.

But you need to use Object.values (not Object.keys).

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

// Note use of Object.values (not Object.keys)
console.log(Object.values(err).some(key => key !== null))

Upvotes: 1

Aneeb
Aneeb

Reputation: 799

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

Upvotes: 2

Related Questions