Skip to content

Instantly share code, notes, and snippets.

@vincelwt
Last active September 18, 2025 18:03
Show Gist options
  • Select an option

  • Save vincelwt/69d3eab2740726d6c58b5ebf905d690a to your computer and use it in GitHub Desktop.

Select an option

Save vincelwt/69d3eab2740726d6c58b5ebf905d690a to your computer and use it in GitHub Desktop.
Search js object
function searchItem(query, obj = window, maxDepth = 10) {
const seen = new WeakSet();
const results = [];
function isMatch(key, value) {
if (String(key).includes(query)) return true;
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
return String(value).includes(query);
}
return false;
}
function recurse(current, path, depth) {
if (depth > maxDepth || current === null) return;
if (typeof current !== "object" && typeof current !== "function") return;
if (seen.has(current)) return;
seen.add(current);
for (let key in current) {
let value;
// Catch getters that throw
try {
value = current[key];
} catch (e) {
continue;
}
const newPath = path.concat(key);
if (isMatch(key, value)) {
results.push({ path: newPath.join("."), key, value });
}
if (typeof value === "object" || typeof value === "function") {
recurse(value, newPath, depth + 1);
}
}
}
recurse(obj, ["window"], 0);
console.log(`Found ${results.length} matches for "${query}":`);
results.forEach(r => {
console.log(r.path, "=", r.value);
});
return results;
}
// Example usage:
searchItem("aid");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment