使用Lodash统计对象中值为undefined的属性数量
统计对象中值为undefined的属性数量
给定如下对象:
let x = { "name": undefined, "value": "tr", "prop1": undefined, "prop2": "test", "prop3": 123 };
需要统计其中值为undefined的属性数量,示例结果为2。以下是几种实用实现方式:
方法一:Object.values + filter组合
通过Object.values提取对象所有属性值组成数组,再用filter筛选出值为undefined的元素,最后取数组长度得到计数:
const count = Object.values(x).filter(val => val === undefined).length; console.log(count); // 输出 2
方法二:for...in循环遍历计数
手动遍历对象的每个属性,逐一判断值是否为undefined并累加计数:
let count = 0; for (const key in x) { // 若需排除继承来的属性,可添加以下判断 // if (x.hasOwnProperty(key)) { if (x[key] === undefined) { count++; } // } } console.log(count); // 输出 2
方法三:Object.entries + reduce累加
通过Object.entries获取对象的键值对数组,用reduce方法累计值为undefined的属性数量:
const count = Object.entries(x).reduce((acc, [_, val]) => val === undefined ? acc + 1 : acc, 0 ); console.log(count); // 输出 2
注意:Object.values和Object.entries默认只处理对象自身的可枚举属性,无需额外判断;而for...in会遍历包括继承来的可枚举属性,若只需统计对象自身属性,记得加上hasOwnProperty判断。
内容的提问来源于stack exchange,提问作者sarsnake
相关产品推荐
相关产品推荐

