0

hi guys I have an object like this

const tmp ={
    identityType:null,
    identityNumber:null,
    nationality:null,
    firstName:null,
    secondName:null,
    gender:null,
    birthDate:null,
    bornCountry:null,
    profession:null,
    province:null,
    city:null,
    address:null,
    postCode:null,
    img:null,
  };

can I check the tmp if all data is not null I will do something ?, I know the easy way just use if , but the data is too much if I'm using If operator ?

just test
  • 273
  • 2
  • 4
  • 9
  • 1
    Use `Object.values()` and `some()` or `every()` – Barmar May 28 '21 at 17:04
  • [Duplicate](//google.com/search?q=site%3Astackoverflow.com+js+check+if+all+object+values+are+non-null) of [Determining if all attributes on a javascript object are null or an empty string](/q/27709636/4642212). Just adapt the conditions of the existing answers, e.g. `Object.values(tmp).every((value) => value !== null)`. – Sebastian Simon May 28 '21 at 22:33

2 Answers2

3

Use the every() method to test if all elements of an array fit some criteria. And Object.values() to get the values in the object as an array.

if (Object.values(tmp).every(el => el !== null)) {
    console.log("All values are not null");
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
2

If you want to check if all values are nulls just check if

Object.values(tmp).filter(el => el !== null).length === 0

The same for all falsey values (null, undefined, 0, etc.)

Object.values(tmp).filter(el => Boolean(el)).length === 0
Virtuoz
  • 896
  • 1
  • 8
  • 14
  • `every` is better than `filter` for this. It doesn't create a new array, and stops as soon as it knows the answer. – Barmar May 28 '21 at 17:07
  • @Barmar, yes indeed, you're right, I simply forgot about `every`. Post your answer and I'll upvote it! – Virtuoz May 28 '21 at 17:08