如何扩展JavaScript代码实现嵌套JSON对象的必填字段验证?
To extend your validation to handle nested properties like primary, city, and street.name.subName, we need to adjust how we define required fields and add a helper function to traverse the nested JSON structure. Here's how to modify your code:
Step 1: Define Required Fields with Full Paths
Instead of just listing top-level keys, specify the full path of each required nested field using dot notation (e.g., address.primary.city):
const myJson = { "type": "typeName", "firstName": "Steven", "lastName": "Smith", "address": { "primary": { "city": "abc", "street": { "name": { "subName": "someName" } } } } }; // List all required fields, including nested paths const requiredFields = [ "firstName", "lastName", "address.primary", "address.primary.city", "address.primary.street.name.subName" ];
Step 2: Helper Function to Check Path Existence
Create a function that takes your JSON object and a field path, then traverses each segment of the path to verify it exists:
function doesFieldExist(obj, fieldPath) { const pathSegments = fieldPath.split('.'); let currentObj = obj; for (const segment of pathSegments) { // Check if the current object has the segment as an own property if (!currentObj || !Object.prototype.hasOwnProperty.call(currentObj, segment)) { return false; } // Move into the nested object for the next iteration currentObj = currentObj[segment]; } return true; }
This function ensures we don't rely on inherited properties (using hasOwnProperty) and stops traversing immediately if any segment of the path is missing.
Step 3: Updated Validation Loop
Use the helper function to check each required field path:
let errors = []; requiredFields.forEach(fieldPath => { if (!doesFieldExist(myJson, fieldPath)) { errors.push(`Missing field: ${fieldPath}`); } }); // Example: Log errors if any console.log(errors); // Outputs an empty array for your sample JSON
How It Works
- For top-level fields like
firstName, the helper function checks directly if the key exists inmyJson. - For nested fields like
address.primary.city, it first checks ifaddressexists inmyJson, thenprimaryinaddress, thencityinprimary. If any of these steps fail, it returnsfalseand we add an error.
Customization Notes
- If you want to validate that the field has a non-empty value (not just existence), modify the helper function to return
trueonly if the final value is truthy (e.g.,return currentObj !== null && currentObj !== undefined;). - You can also define paths using arrays (e.g.,
["address", "primary", "city"]) instead of dot notation if that fits your workflow—just adjust the helper function to iterate over the array directly.
内容的提问来源于stack exchange,提问作者user2281858

