如何使用Filter匹配JSON键值对并验证键值对是否存在?
Check if a Specific Key-Value Pair Exists in JSON
Hey, nice job getting the key existence check working already! To add value matching, it’s just a small extension to your existing logic—let’s break this down step by step.
Core Idea
First, you’ll want to:
- Reuse your existing logic to confirm the target key exists in the object
- If the key exists, compare its value against your expected target value
Basic Implementation (for Primitive Values)
If you’re working with primitive values (strings, numbers, booleans, null/undefined), a simple strict equality check (===) will work perfectly. Here’s how to modify your function:
function checkFilterKeyValueMatch(obj, filterKey, targetValue) { // Step 1: Check if the key exists (your existing logic) if (!obj.hasOwnProperty(filterKey)) { return false; } // Step 2: Compare the value to your target return obj[filterKey] === targetValue; }
Example Usage
// Sample JSON object const myData = { Filter: "completed", Priority: "high", Items: [1, 2, 3] }; // Check if "Filter" exists and equals "completed" console.log(checkFilterKeyValueMatch(myData, "Filter", "completed")); // true // Check if "Filter" exists and equals "pending" console.log(checkFilterKeyValueMatch(myData, "Filter", "pending")); // false // Check for a non-existent key console.log(checkFilterKeyValueMatch(myData, "Status", "active")); // false
Handling Complex Values (Objects/Arrays)
If your target value is an object or array, strict equality (===) only checks if they reference the same object in memory. For deep value comparison, you’ll need a helper function:
// Helper function for deep equality check function deepEqual(a, b) { // Check strict equality first for primitives if (a === b) return true; // Handle null/undefined cases if (a == null || typeof a !== "object" || b == null || typeof b !== "object") { return false; } // Compare object keys and their values recursively const keysA = Object.keys(a); const keysB = Object.keys(b); if (keysA.length !== keysB.length) return false; for (const key of keysA) { if (!keysB.includes(key) || !deepEqual(a[key], b[key])) { return false; } } return true; } // Modified function for deep value matching function checkFilterKeyValueMatchDeep(obj, filterKey, targetValue) { if (!obj.hasOwnProperty(filterKey)) { return false; } return deepEqual(obj[filterKey], targetValue); }
Example with Complex Values
const complexData = { Filter: { status: "active", minScore: 80 } }; // Expected target value const expectedFilter = { status: "active", minScore: 80 }; console.log(checkFilterKeyValueMatchDeep(complexData, "Filter", expectedFilter)); // true
Key Notes
- Use strict equality (
===) instead of loose equality (==) to avoid unexpected type coercion issues. - The deep equality helper works for most standard objects/arrays—if you need to handle edge cases like dates or functions, you can extend it further.
内容的提问来源于stack exchange,提问作者user1093111
相关产品推荐
相关产品推荐

