Search code examples
javascriptarraysecmascript-6ecmascript-2016

How to skip an element when using every


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


Solution

  • 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 completely 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.