How do you find all values for a key in a nested JSON object recursively?
function findKeys(obj, target, results = []) { Object.keys(obj).forEach(key => { if (key === target) results.push(obj[key]); if (typeof obj[key] === 'object') findKeys(obj[key], target, results); }); return results; }
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Recursion for Tree Traversal in JavaScript
function traverse(node) { callback(node); if (node.children) node.children.forEach(child => traverse(child)); }. Process the current node, then recurse into each child. The base case is implicit (no children = no recursion).
function walkDOM(node, callback) { callback(node); Array.from(node.children).forEach(child => walkDOM(child, callback)); }. Call the callback on the current node, then recurse into each child element.
function inorder(node) { if (!node) return; inorder(node.left); console.log(node.value); inorder(node.right); }. Visit left subtree, then root, then right subtree. Returns values in sorted order for a BST.
Still have questions?
Browse all our FAQs or reach out to our support team
