Last active
May 31, 2018 23:13
-
-
Save montyr75/bbc2bb53c0906c0aa85bd60075b3f339 to your computer and use it in GitHub Desktop.
Searching for all instances of "key" in an object with TypeScript.
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
class Utils { | |
static search(name: String, obj: any, results: Array<any>) { | |
for (var key in obj) { | |
if (obj.hasOwnProperty(key)) { | |
const value = obj[key]; | |
if (key == name) { | |
results.push(value); | |
} | |
else if (typeof value === 'object') { | |
Utils.search(name, value, results); | |
} | |
} | |
} | |
} | |
static searchByNodeType(type: String, obj: any, results: Array<any>) { | |
for (var key in obj) { | |
if (obj.hasOwnProperty(key)) { | |
const value = obj[key]; | |
if (typeof value === 'object') { | |
if (value['_type'] == type) { | |
results.push({ "name": key, "value": value }); | |
} | |
else { | |
Utils.searchByNodeType(type, value, results); | |
} | |
} | |
} | |
} | |
} | |
} | |
// EXAMPLE USAGE (Create a results array to store output.) | |
let results: Array<any> = []; | |
Utils.search("_power", org, results); | |
console.log(results); | |
results = []; | |
Utils.searchByNodeType("hotdrop", org, results); | |
console.log(results); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment