Last active
September 21, 2019 22:11
-
-
Save lcherone/f270f73cfd7f91bba09793e0166a62be to your computer and use it in GitHub Desktop.
traverse recursive enumerate javascript object safe from [Circular] reference
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
/** | |
* Traverse over an object, safe from [Circular] | |
* | |
* - if value is string or number, returns value | |
* - if value is function, returns array of function arguments | |
* - if value is anything else, returns empty string | |
* | |
``` javascript | |
let test = { | |
// [Circular] | |
test: test, | |
a: function (paramA, paramB, paramC) { | |
return { | |
b: {} | |
} | |
}, | |
b: 'a string', | |
c: 134, | |
d: [{ | |
a: new Date() | |
}] | |
} | |
console.log(objectEnum(test)) | |
{ | |
test:"", | |
a: [ | |
"paramA", | |
"paramB", | |
"paramC" | |
], | |
b: "a string", | |
c: 134, | |
d: [{ | |
a: "2019-09-21T21:44:46.422Z" | |
}] | |
} | |
``` | |
*/ | |
function objectEnum(object) { | |
let cache = [] | |
const str = JSON.stringify(object, function (key, value) { | |
if (typeof value === 'object' && value !== null) { | |
if (cache.indexOf(value) !== -1) { | |
return | |
} | |
cache.push(value) | |
} | |
return typeof value === 'object' ? value : (typeof value === 'function' ? (function (func) { | |
const fnStr = func.toString().replace(/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg, '') | |
return fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(/([^\s,]+)/g) || [] | |
})(value) : (['string', 'number'].includes(typeof value) ? value : '')) | |
}, 0) | |
cache = null | |
try { | |
return JSON.parse(str) | |
} catch (e) { | |
return {} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment