Last active
August 31, 2017 09:46
-
-
Save vaidd4/5000931391538163ebb7a17eca7ba5f6 to your computer and use it in GitHub Desktop.
A function to make deep checking on objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Run a simple check on every attribute of an object | |
* It returns true if any attribute (non object) passes the test function | |
*/ | |
function checkDeep(obj, fun) { | |
for (let k in obj) { | |
if (!obj.hasOwnProperty(k)) continue | |
if (Array.isArray(obj[k])) { | |
if (obj[k].some(fun)) | |
return true | |
} | |
else if (obj[k] === Object(obj[k])) { | |
if (checkDeep(obj[k], fun)) | |
return true | |
} | |
else if (fun(obj[k], k, obj)) | |
return true | |
} | |
return false | |
} | |
/** | |
* Example with a simple object | |
*/ | |
let obj = { | |
a: '1', | |
b: { | |
c: '3', | |
d: ['A', 'B', 'C'] | |
}, | |
e: { | |
f: { | |
g: '' // should stop here | |
}, | |
h: '8' | |
} | |
} | |
checkDeep(obj, (v, i, a) => { | |
console.log(`a[${i}] = ${v}; a:`, a) | |
return !v | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment