Last active
August 3, 2024 05:21
-
-
Save nikhilweee/ec2ed250212e544120b6198ec70d7cce to your computer and use it in GitHub Desktop.
Search for nested values in a JS object
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
function search(obj, string) { | |
const maxDepth = 10; | |
const excludeKeys = ["_root"]; | |
function isObject(val) { | |
return typeof val === "function" || typeof val === "object"; | |
} | |
function traverse(obj, depth, path) { | |
// Guard clause | |
if (depth > maxDepth) { | |
return; | |
} | |
if (obj === null) { | |
// Helps simplify object checking | |
return; | |
} else if (isObject(obj)) { | |
// Handle objects | |
for ([key, value] of Object.entries(obj)) { | |
if (excludeKeys.includes(key)) { | |
continue; | |
} | |
traverse(value, depth + 1, path.concat(key)); | |
} | |
} else if (Array.isArray(obj)) { | |
// Handle arrays | |
obj.forEach((item, index) => { | |
traverse(item, depth + 1, path.concat(index)); | |
}); | |
} else { | |
// Handle primitive data types | |
if (String(obj).includes(string)) { | |
console.log(`${path.join(".")}: ${obj}`); | |
} | |
} | |
} | |
traverse(obj, 0, []); | |
} | |
// Example usage: | |
const obj = { | |
key1: "value1", | |
nested: { | |
key2: "needle here", | |
key3: 42, | |
deeper: { | |
key4: "still going", | |
more: { | |
key5: "needle again", | |
evenDeeper: { | |
key6: "deepest needle", | |
}, | |
}, | |
}, | |
}, | |
array: [1, "needle", { key7: "value7" }], | |
}; | |
search(obj, "needle"); | |
// Expected Output | |
// nested.key2: needle here | |
// nested.deeper.more.key5: needle again | |
// nested.deeper.more.evenDeeper.key6: deepest needle | |
// array.1: needle |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment