简体   繁体   中英

Javascript - Checking an object for null or empty key values

I recently ran into a situation at work where I needed to check for null or empty keys inside an object dynamically. I looked online and saw some similar solution, but I managed to toss a function together that's pretty succinct and I was hoping to share it for whomever might benefit and get some feedback.

function allKeysValid(obj) {
    return !Object.keys(obj).some(key => null == obj[key] || "" === obj[key])
}

Hope someone can get use out of it.

It's like this:

 addEventListener('load', function(){ function completeObj(obj){ for(var i in obj){ var v = obj[i]; if(!v && v !== 0){ return false; } } return true; } var objA = {a:'will fail', b:false, c:true}; var objB = {cool:'will pass', neat:0, fun:'maybe'}; var loop = [objA, objB], completes = []; for(var i=0,o,l=loop.length; i<l; i++){ o = loop[i]; if(completeObj(o)){ completes.push(o); } } console.log(completes); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM