admin管理员组

文章数量:1430112

I have an object:

obj = {name:null, lastName:null, scores:[]}

I need to iterate and check whether all fields are null , except for the scores field. I need to skip that.

I was using

  Object.values(obj).every(x=> x===null) 

before the scores was added, but I'm not sure how to skip that field now. Because regardless if the scores array is empty or not, if all other fields are null I need to return true.

Any suggestion is appreciated

I have an object:

obj = {name:null, lastName:null, scores:[]}

I need to iterate and check whether all fields are null , except for the scores field. I need to skip that.

I was using

  Object.values(obj).every(x=> x===null) 

before the scores was added, but I'm not sure how to skip that field now. Because regardless if the scores array is empty or not, if all other fields are null I need to return true.

Any suggestion is appreciated

Share Improve this question edited May 3, 2019 at 16:59 Salman Arshad 273k84 gold badges444 silver badges534 bronze badges asked Feb 26, 2019 at 9:29 user10658941user10658941 7
  • 1 I think there's a mistake in your code... shouldn't it be obj[x] === null? – Pedro LM Commented Feb 26, 2019 at 9:33
  • Object.keys(obj).every(x=> x==='scores' || x===null) – arizafar Commented Feb 26, 2019 at 9:34
  • What's your end goal? Are you trying to filter out the null values? – StudioTime Commented Feb 26, 2019 at 9:35
  • @AZ_ that doesn't work, you're paring x (the key) to null, not the value. – Alnitak Commented Feb 26, 2019 at 9:43
  • yea @Alnitak already noticed, but cannot update. must be obj[x], I just cared about skipping the score as asked in question and didnt check the rest code. – arizafar Commented Feb 26, 2019 at 9:45
 |  Show 2 more ments

2 Answers 2

Reset to default 6

You could filter the keys you do not want to check:

Object.keys(obj)
    .filter(k => k !== "scores")
    .every(k => obj[k] === null);

It is possible to bine the two conditions inside every (just return true for keys you do not want to check) but I chose to keep the logic separate.

If you can use ES7 (and shims are available if you can't) you can use this which avoids iterating over the object twice:

Object.entries(obj).every(([k, v]) => v === null || k === 'scores');

Object.entries works in every current mainstream browser except MSIE.

The other advantage of Object.entries is that since the callback is passed both the key and the value, there's no need to access obj within the callback, which in turn forces the use of an inline function forming a closure over obj. With .entries() it's pletely possible to make the callback a separate function, which would be especially important if the code were to get much longer, or if that callback logic was required in multiple places.

本文标签: javascriptHow to skip an element when using everyStack Overflow