Last active
April 3, 2018 05:27
-
-
Save usametov/78e9453db0352f8207d43673e7f673e0 to your computer and use it in GitHub Desktop.
traverse object tree in javascript
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
//this will hopefully run in debug mode | |
//https://www.jetbrains.com/help/webstorm/running-and-debugging-node-js.html#ws_node_debugging_debugger_console | |
function traverse(o ) { | |
for (i in o) { | |
if (!!o[i] && typeof(o[i])=="object") { | |
// use typescript instanceof operator here | |
// we should be able to travel to desired type | |
console.log(i, o[i]) | |
traverse(o[i] ); | |
} | |
} | |
} | |
//another example: | |
function traverse(jsonObj) { | |
// use typescript instanceof operator here | |
// we should be able to travel to desired type | |
if( typeof jsonObj == "object" ) { | |
Object.entries(jsonObj).forEach(([key, value]) => { | |
// key is either an array index or object key | |
traverse(value); | |
}); | |
} | |
else { | |
// jsonObj is a number or string | |
} | |
} | |
//for nulls call this one: | |
class InstanceLoader { | |
static getInstance<T>(context: Object, name: string, ...args: any[]) : T { | |
var instance = Object.create(context[name].prototype); | |
instance.constructor.apply(instance, args); | |
return <T> instance; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment