如何检测对象是否包含指定嵌套属性以外的其他属性
判断对象是否包含已知嵌套属性以外的额外属性
要解决嵌套属性的检测问题,我们可以通过构建允许的属性结构,再递归对比对象的每一层属性来实现,具体步骤如下:
实现思路
- 将已知的点分隔属性路径(如
props.abc)转换成嵌套的允许结构对象,明确哪些属性(包括嵌套层级)是被允许的。 - 递归遍历目标对象,检查每一层属性是否在允许结构中:如果发现某层存在不在允许结构里的属性,就判定存在额外属性。
代码实现
// 将已知属性路径转换为嵌套的允许结构 function buildAllowedStructure(knownProps) { const allowed = {}; for (const path of knownProps) { const keys = path.split('.'); let current = allowed; for (const key of keys) { current[key] = current[key] || {}; current = current[key]; } } return allowed; } // 递归检查对象是否包含额外属性 function hasExtraProperties(obj, knownProps) { const allowedStructure = buildAllowedStructure(knownProps); function checkExtra(currentObj, currentAllowed) { for (const key of Object.keys(currentObj)) { // 当前属性不在允许结构中,说明是额外属性 if (!currentAllowed.hasOwnProperty(key)) { return true; } const value = currentObj[key]; // 如果是对象(非null、非数组),继续递归检查子属性 if (typeof value === 'object' && value !== null && !Array.isArray(value)) { if (checkExtra(value, currentAllowed[key])) { return true; } } } return false; } return checkExtra(obj, allowedStructure); }
测试示例
用你提供的对象和已知属性进行测试:
const obj = { props: { abc: { def: 1 }, ghi: { jkl: 2 } }, xyz: 3 }; const someKnownProps = ["props.abc", "xyz"]; console.log(hasExtraProperties(obj, someKnownProps)); // 输出 true(检测到props.ghi这个额外属性)
扩展说明
- 上述代码默认允许已知属性的子属性任意存在(比如
props.abc.def是被允许的),如果需要限制子属性,只需在已知属性路径中添加完整的子路径(如props.abc.def)。 - 如果需要支持数组类型的属性,可以在
checkExtra函数中添加数组判断逻辑,遍历数组元素进行递归检查。
内容的提问来源于stack exchange,提问作者Khurram W. Malik
相关产品推荐
相关产品推荐

