Invalidate a JS Object when any of its values is null or empty I created a simple Javascript method to recursively parse a JS Object and find out if any of its values or sub values is set to null or is empty string.

I could't break on when using Array.map() or Array.forEach() so I went with this :

const isValidObject = (obj) =&gt; {
  let invalid = []
  const validate = (obj) =&gt; {
    Object.values(obj).map(el =&gt; {
      if (typeof el === 'object') {
        validate(el)
      } else if (el === null || el === '') {
        invalid.push(el)
      }
    })
    return invalid.length === 0
  }
  return validate(obj)
}


If you have any opinonated or objective thought about this way of doing, please share it with me.



const isValidObject = (obj) =&gt; {
  let invalid = []
  const validate = (obj) =&gt; {
    Object.values(obj).map(el =&gt; {
      if (typeof el === 'object') {
        validate(el)
      } else if (el === null || el === '') {
        invalid.push(el)
      }
    })
    return invalid.length === 0
  }
  return validate(obj)
}

let toto = {
 name: 'toto',
  age: 12,
  pony: {
    name: 'rainbow dash',
    age: ''
  }
}

console.log('test :', isValidObject(toto))
Say hello to your new friend, Array.prototype.every. You'll have a callback which actually returns false on any element which is null or ''. The .every call will be short-circuited and your iteration won't have to go over all the nested elements. No need for extraneous invalid array either.