如何将生成建议数组的JavaScript函数改为递归并移除for-in循环
Recursive Solution Without For-In Loops for Suggestion Generation
Got it, let's refactor this into a recursive solution that ditches those for-in loops and correctly generates full suggestions like Maark or Maary. The core idea is to traverse the nested object recursively, build up the suffix string as we go, and collect the final suggestions when we reach the leaf nodes (where the value is 0).
Revised Code
function get_suggestion_array_from_object() { const test_searchstring = 'Ma'; const test_current_object = JSON.parse('{"a":{"r":{"k":0,"y":0}, "s":{"s":0,"y":0}}}'); const suggestion_array = []; // Recursive helper to traverse the nested object const traverseNested = (currentObj, currentSuffix = '') => { // Use Object.keys to get all keys, iterate with forEach (no for-in) Object.keys(currentObj).forEach(key => { const updatedSuffix = currentSuffix + key; // Check if we've reached a leaf node (value is 0) if (currentObj[key] === 0) { suggestion_array.push(test_searchstring + updatedSuffix); } else { // Recurse into the next level of the object traverseNested(currentObj[key], updatedSuffix); } }); }; // Start traversing from the root object traverseNested(test_current_object); // Log or return the result console.log(suggestion_array); // Output: ["Maark", "Maary", "Maass", "Maasy"] return suggestion_array; } get_suggestion_array_from_object();
Key Improvements & Explanations
- No more for-in loops: We use
Object.keys()to get an array of the object's own enumerable keys, then iterate withforEach—this avoids unexpected behavior from inherited properties that can come with for-in, and meets your requirement to remove those loops. - Recursive depth handling: Unlike the original code which only traversed two hardcoded levels, this solution works for any depth of nested objects. If your structure grows deeper later, it'll still generate the correct suggestions.
- Clear leaf node detection: When we hit a key with a value of
0(your marker for the end of a suggestion path), we combine the base search string with the built-up suffix and add it to the result array. - Cleaner state management: The recursive helper function uses a
currentSuffixparameter to track the string we're building as we traverse, keeping the logic focused and easy to follow.
内容的提问来源于stack exchange,提问作者imraihan
相关产品推荐
相关产品推荐

