是否存在JavaScript/Lodash函数可检查对象是否缺失任意属性?
简洁检查JavaScript对象是否存在缺失属性的方法
不用逐个写hasOwnProperty或if/else,下面是几种简洁的实现方式:
1. 基于必填属性数组的批量检查
先定义所有必填属性的数组,再用数组的every()方法批量验证:
仅检查属性是否存在(不管值是什么)
const requiredProps = ['name', 'age', 'email']; const targetObj = { name: 'Alice', age: 30, email: 'alice@example.com' }; // 检查对象是否拥有所有必填属性(不考虑继承属性) const hasAllProps = requiredProps.every(prop => targetObj.hasOwnProperty(prop)); console.log(hasAllProps); // 输出 true
同时检查属性存在且值不为null/undefined
如果需要确保属性值不是null或undefined,可以调整判断逻辑:
const hasValidProps = requiredProps.every(prop => targetObj[prop] != null); // != null 会同时排除 null 和 undefined,允许0、false、''等假值
2. 解构赋值配合标记值快速验证
利用解构赋值的默认值特性,给缺失的属性设一个特殊标记,再检查是否存在该标记:
const checkRequiredProps = ({ name = '__MISSING__', age = '__MISSING__', email = '__MISSING__' }) => !Object.values({ name, age, email }).includes('__MISSING__'); // 使用示例 const validObj = { name: 'Bob', age: 25, email: 'bob@example.com' }; const invalidObj = { name: 'Charlie', email: 'charlie@example.com' }; console.log(checkRequiredProps(validObj)); // true console.log(checkRequiredProps(invalidObj)); // false
3. 封装通用检查函数
把逻辑封装成可复用的函数,方便多处调用:
function validateObjectProps(obj, requiredProps, checkValue = false) { if (checkValue) { return requiredProps.every(prop => obj.hasOwnProperty(prop) && obj[prop] != null); } return requiredProps.every(prop => obj.hasOwnProperty(prop)); } // 使用示例 const testObj = { name: 'Dave', age: undefined, email: 'dave@example.com' }; // 仅检查属性存在 console.log(validateObjectProps(testObj, ['name', 'age', 'email'])); // true // 检查属性存在且值有效 console.log(validateObjectProps(testObj, ['name', 'age', 'email'], true)); // false
4. 检查继承属性(可选)
如果需要包括对象继承来的属性,可以用Reflect.has()替代hasOwnProperty:
const hasAllInheritedProps = requiredProps.every(prop => Reflect.has(targetObj, prop));
内容的提问来源于stack exchange,提问作者Laura Drill
相关产品推荐
相关产品推荐

