如何判断两个嵌套对象中是否存在至少一处真值匹配?
Solution to Check for Matching True Values in Nested Objects
To solve this problem, we can use a recursive approach to traverse both nested objects, checking each key in the need object against the corresponding key in have to see if both hold a true value. This avoids converting objects to arrays and handles nested structures naturally.
Step-by-Step Explanation
- Recursive Helper Function: We'll create a function that takes segments of
haveandneed(starting with the full objects) and checks each key in the currentneedsegment. - Handle Nested Objects: If a key's value is an object (and not
null), we recursively call the helper function on the nested objects. - Check for True Matches: For non-object values, we check if both
haveandneedhavetrueat that key. If we find any such match, we immediately returntrue(since we only need at least one). - No Matches Found: If we finish traversing all keys without finding a match, return
false.
Implementation Code
function hasMatchingTrue(haveObj, needObj) { // Iterate over every key present in the need object for (const key in needObj) { const haveValue = haveObj[key]; const needValue = needObj[key]; // Skip if the key doesn't exist in have (though problem states need won't have extra keys) if (haveValue === undefined) continue; // If both values are non-null objects, recurse into them if (typeof haveValue === 'object' && haveValue !== null && typeof needValue === 'object' && needValue !== null) { if (hasMatchingTrue(haveValue, needValue)) { return true; } } else { // Check if both values are strictly true if (haveValue === true && needValue === true) { return true; } } } // No matching true values found in any corresponding keys return false; }
Test Cases
Let's verify the function with your examples and edge cases:
Example 1: Basic Nested Match
const have = { a: true, b: { c: true, d: true } }; const need = { a: false, b: { c: true, d: false } }; console.log(hasMatchingTrue(have, need)); // Output: true (matches at b.c)
Example 2: Need with Fewer Keys
const need2 = { b: { c: true } }; console.log(hasMatchingTrue(have, need2)); // Output: true (matches at b.c)
Example 3: No Matching Trues
const need3 = { a: false, b: { d: false } }; console.log(hasMatchingTrue(have, need3)); // Output: false
Example 4: Deeply Nested Objects
const have4 = { x: { y: { z: true } } }; const need4 = { x: { y: { z: true } } }; console.log(hasMatchingTrue(have4, need4)); // Output: true const need5 = { x: { y: { z: false } } }; console.log(hasMatchingTrue(have4, need5)); // Output: false
This approach efficiently traverses only the keys present in need (as per the problem constraints) and stops as soon as it finds the first matching true value, making it optimal for most use cases.
内容的提问来源于stack exchange,提问作者Mariano Zunino
相关产品推荐
相关产品推荐

