You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何扩展JavaScript代码实现嵌套JSON对象的必填字段验证?

Validating Nested JSON Fields for Required Values

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 in myJson.
  • For nested fields like address.primary.city, it first checks if address exists in myJson, then primary in address, then city in primary. If any of these steps fail, it returns false and 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 true only 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 05:07:35