Skip to content

Instantly share code, notes, and snippets.

@legraphista
Created April 2, 2023 13:00
Show Gist options
  • Save legraphista/eea8a8fa47aac08664467c1cb9b6ff83 to your computer and use it in GitHub Desktop.
Save legraphista/eea8a8fa47aac08664467c1cb9b6ff83 to your computer and use it in GitHub Desktop.
Find a needle in a heystack in Typescript (walk object and find path of a structure)
export function find(hayStack: any, magnifier: (path: string[], key: string, value: any) => boolean) {
const foundPaths: { path: string[], key: string, value: unknown }[] = [];
function walk(obj: any, path: string[]) {
// console.log(path.join('.'), obj)
if (magnifier(path, path[path.length - 1], obj)) {
foundPaths.push({
path: path.slice(0, path.length - 1),
key: path[path.length - 1],
value: obj
})
}
if (typeof obj === 'object' && obj !== null) {
for (const [k, v] of Object.entries(obj)) {
walk(v, path.concat(k));
}
}
}
walk(hayStack, []);
return foundPaths;
}
export function walkObjectByPath<T>(obj: any, path: string[]):T|undefined {
let cursor = obj;
for (const key of path) {
cursor = cursor?.[key];
}
return cursor;
}
// example
const hey = {
this: {
is: {
an: {
unknown: {
object: {
a : 1
}
}
}
}
}
}
const needles = find(hey, (path, key, value) => key === 'a' && value ===1);
console.log(needles);
/*
[
{
path: [ 'this', 'is', 'an', 'unknown', 'object' ],
key: 'a',
value: 1
}
]
*/
const data = walkObjectByPath(hey, needles[0].path)
console.log(data)
// { a: 1 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment