Skip to content

Instantly share code, notes, and snippets.

@montyr75
Last active May 31, 2018 23:13
Show Gist options
  • Save montyr75/bbc2bb53c0906c0aa85bd60075b3f339 to your computer and use it in GitHub Desktop.
Save montyr75/bbc2bb53c0906c0aa85bd60075b3f339 to your computer and use it in GitHub Desktop.
Searching for all instances of "key" in an object with TypeScript.
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