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

如何统计表单嵌套对象的已填充属性与总属性数量?

计算嵌套表单对象的填充字段数与总字段数

要统计嵌套对象的总字段数和已填充字段数,可通过递归遍历对象属性实现,同时明确“已填充”的判断规则(排除null、undefined、空字符串""这类无效值)。

实现代码

function countFormFields(obj) {
  let total = 0;
  let filled = 0;

  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      total++;
      const value = obj[key];

      // 处理嵌套对象
      if (typeof value === 'object' && value !== null) {
        const nestedStats = countFormFields(value);
        total += nestedStats.total;
        filled += nestedStats.filled;
      } else {
        // 判断当前字段是否为有效填充值
        if (value !== null && value !== undefined && value !== '') {
          filled++;
        }
      }
    }
  }

  return { total, filled };
}

// 测试示例表单
const form = {
  name: "Jonh",
  age: null,
  email: "jonh@mail.com",
  address: {
    street: "This is a street",
    city: undefined
  },
  socialMedia: {
    facebook: "",
    twitter: "@jonh"
  }
};

// 获取统计结果
const { total, filled } = countFormFields(form);
console.log(`总字段数:${total}`); // 输出 7
console.log(`已填充字段数:${filled}`); // 输出 4
console.log(`填充百分比:${((filled / total) * 100).toFixed(2)}%`); // 输出 57.14%

逻辑说明

  1. 递归遍历:遍历对象的每个自有属性(通过hasOwnProperty过滤原型链属性),每遇到一个属性就累加总字段数。
  2. 嵌套对象处理:如果属性值是对象且不为null,递归调用统计函数,将嵌套对象的统计结果合并到当前结果中。
  3. 填充判断:非对象类型的值,只要不是null、undefined或空字符串,就视为已填充字段,累加已填充计数。

自定义规则

如果需要调整“已填充”的判断标准(比如允许空数组、特定格式的空值),只需修改非对象值的判断条件即可。

内容的提问来源于stack exchange,提问作者Martim Silva

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 21:30:41