如何在未知结构的多维对象中检测指定键值对是否存在?
Detecting a Specific Key-Value Pair in Arbitrary, Nested Objects
Absolutely, you can detect a target key-value pair in any object—regardless of its type, depth, or structure—using a recursive traversal approach. Here's how to do it cleanly:
Core Logic
The idea is to:
- Check if the current item is an object or array (since your example includes nested arrays of objects).
- For objects: Verify if it contains the target key with the exact value. If yes, return true immediately. If not, recursively check every value in the object.
- For arrays: Iterate through each element and recursively check each one.
- For primitive values (strings, numbers, null, etc.): Skip them since they can't contain key-value pairs.
Example Implementation (JavaScript)
Let's write a function tailored to your use case (looking for "kod": "REVH"):
function hasKeyValuePair(targetObj, targetKey, targetValue) { // Check if current item is a valid object (exclude null, since typeof null is "object") if (typeof targetObj === 'object' && targetObj !== null) { // Check if the current object has the target key with a matching value if (targetObj.hasOwnProperty(targetKey) && targetObj[targetKey] === targetValue) { return true; } // Recursively check every value in the object/array for (const value of Object.values(targetObj)) { if (hasKeyValuePair(value, targetKey, targetValue)) { return true; } } } // No match found in this branch return false; }
Testing with Your Sample Data
Using your provided target object (I completed the truncated section for testing):
const targetObject = { "names": [ { "name1": "xxx", "name2": "yyy", "pn": null, "functions": [ { "kod": "LE", "text": "test" }, { "kod": "VD", "text": "test" } ] }, { "name1": null, "name2": "Comp", "pn": null, "pn2": "1239992", "functions": [ { "kod": "REV", "text": "temp" } ] }, { "name1": "Peter", "name2": "name", "pn": "abc123", "functions": [ { "kod": "REVH", "text": "matched!" } // Added to test a successful match ] } ] }; // Check for the target key-value pair console.log(hasKeyValuePair(targetObject, "kod", "REVH")); // Output: true
Edge Cases to Consider
- Circular References: If your object has circular references (e.g., an object that references itself), the basic function will cause an infinite loop. Here's a modified version to handle this:
function hasKeyValuePair(targetObj, targetKey, targetValue, visited = new Set()) { if (typeof targetObj === 'object' && targetObj !== null) { // Skip objects we've already checked to avoid loops if (visited.has(targetObj)) return false; visited.add(targetObj); if (targetObj.hasOwnProperty(targetKey) && targetObj[targetKey] === targetValue) { return true; } for (const value of Object.values(targetObj)) { if (hasKeyValuePair(value, targetKey, targetValue, visited)) { return true; } } } return false; } - Loose Equality: If you need to match values loosely (e.g.,
123vs"123"), swap the strict equality check (===) for==, but strict equality is safer for most use cases.
This approach is flexible and works for any nested structure you throw at it.
内容的提问来源于stack exchange,提问作者Kevin Lindmark
相关产品推荐
相关产品推荐

