如何使用 Lodash 统计对象中值为 undefined 的属性数量

如何使用 Lodash 统计对象中值为 undefined 的属性数量

本文介绍如何高效统计 javascript 对象中值严格等于 undefined 的属性个数,涵盖原生方法与 lodash 两种实现方式,并强调严格相等判断、避免类型误判等关键细节。

在实际开发中,我们常需分析对象状态——例如检测哪些字段尚未初始化(即值为 undefined)。注意:这不同于 null、空字符串、0 或 false,必须是严格意义上的 undefined。

以下是对给定对象的两种推荐方案:

✅ 原生 JavaScript(推荐,无依赖)
利用 Object.values() 提取所有属性值,再通过 filter() 筛选严格等于 undefined 的项,最后取长度:

const x = {
  "name": undefined,
  "value": "tr",
  "prop1": undefined,
  "prop2": "test",
  "prop3": 123
};

const undefinedCount = Object.values(x).filter(v => v === undefined).length;
console.log(undefinedCount); // → 2

✅ Lodash 方式(语义清晰,兼容旧环境)
使用 _.filter(object, predicate) 遍历键值对,返回所有满足条件的值组成的数组,再取 .length:

const _ = require('lodash');

const undefinedCount = _.filter(x, (v, k) => v === undefined).length;
console.log(undefinedCount); // → 2

⚠️ 重要注意事项

GitHub Copilot

GitHub Copilot

GitHub AI编程工具,实时编程建议

下载

  • 必须使用 === undefined(严格相等),避免 == undefined(会错误匹配 null);
  • 不要使用 v == null 或 v == undefined,否则会将 null 也计入;
  • _.countBy() 或 _.size(_.pickBy(x, _.isUndefined)) 虽可行,但性能较低且冗余;
  • Object.keys(x).filter(k => x[k] === undefined).length 同样有效,但 Object.values() 更直观简洁。

总结:若项目已引入 Lodash,可选用其 filter 方法以提升可读性;否则优先使用原生 Object.values().filter().length——简洁、高效、无需额外依赖。

https://www.php.cn/faq/2038511.html

发表回复

Your email address will not be published. Required fields are marked *