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

如何在JavaScript函数中遍历JSON格式的表单验证错误对象节点

表单验证错误对象的遍历解决方案

问题背景

PHP服务端验证后返回JSON格式的错误数据,其中errors字段是一个以表单字段名为键、对应错误消息数组为值的对象。前端需要遍历该对象,依次获取字段名和对应的错误消息,但原遍历代码因对象不可直接用for...of遍历而失效。

相关代码片段

PHP返回代码

...
echo json_encode($response);
exit;

返回的JSON数据

{"status":"error","html":"<p class='error'>There are errors, please check over the form.<\/p>","errors":{"title":["This field was empty. ", "There are formatting errors also"]}}

前端fetch处理代码

fetch(the_form.getAttribute('action'), { method: $method, headers: {"X-Requested-With": "XMLHttpRequest"}, body: new FormData(the_form) })
            .then(response => response.json())
            .then(function (data) {
            if (data.status == "success") {
                 // DO SUCCESS STUFF
            } else {
                 display_validation_errors(data.errors);
            }
}

正确的遍历实现

由于errors是普通对象而非数组,不能直接使用for...of遍历,以下是两种可行的实现方式:

方式1:使用Object.entries()直接遍历键值对

function show_validation_errors(errors) {
    // 遍历对象的每个键值对,fieldName是字段名,errorMessages是对应错误数组
    for (const [fieldName, errorMessages] of Object.entries(errors)) {
        console.log(fieldName); // 输出示例:"title"
        // 遍历当前字段的所有错误消息
        for (const message of errorMessages) {
            console.log(message); // 输出示例:"This field was empty. "
        }
    }
}

方式2:使用Object.keys()先获取字段名数组

function show_validation_errors(errors) {
    // 获取所有表单字段名组成的数组
    const fieldNames = Object.keys(errors);
    for (const fieldName of fieldNames) {
        console.log(fieldName);
        // 通过字段名获取对应的错误消息数组
        const errorMessages = errors[fieldName];
        for (const message of errorMessages) {
            console.log(message);
        }
    }
}

原代码错误原因

原代码中for (let error of errors)的写法不适用于普通对象,因为for...of仅支持遍历具备可迭代接口的对象(如数组、字符串、Map等),而普通对象默认不具备该特性,因此需要借助Object.entries()或Object.keys()将对象转换为可遍历的结构。

内容的提问来源于stack exchange,提问作者Scott Richardson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 14:18:36