如何判断指定key是否存在于对象的嵌套对象及数组结构中
解决方案
实现原理
原生的in运算符和hasOwnProperty方法仅支持检测当前对象的直属属性,想要支持嵌套对象、数组的检测,需要通过递归遍历所有嵌套结构的节点,逐层校验属性是否存在。
代码实现
版本1:包含原型链属性检测(和in运算符逻辑一致)
function hasNestedKey(target, searchKey) { // 非对象/数组类型直接返回false if (typeof target !== 'object' || target === null) { return false } // 先检查当前层是否存在目标key if (searchKey in target) { return true } // 遍历所有属性值递归检查 for (const value of Object.values(target)) { if (hasNestedKey(value, searchKey)) { return true } } return false }
版本2:仅检测对象自身属性(和hasOwnProperty逻辑一致,排除原型链属性)
function hasNestedOwnProperty(target, searchKey) { if (typeof target !== 'object' || target === null) { return false } if (target.hasOwnProperty(searchKey)) { return true } for (const value of Object.values(target)) { if (hasNestedOwnProperty(value, searchKey)) { return true } } return false }
使用示例
嵌套对象测试:
const myObject = { name: 'Joe', favorites: { ice_cream: 'vanilla', coffee: 'espresso' } } console.log(hasNestedKey(myObject, 'coffee')) // 输出 true console.log(hasNestedOwnProperty(myObject, 'coffee')) // 输出 true
数组场景测试:
const testData = { list: [ { id: 1, name: 'A' }, { id: 2, desc: '测试' } ] } console.log(hasNestedKey(testData, 'desc')) // 输出 true
内容的提问来源于stack exchange,提问作者aaron
相关产品推荐
相关产品推荐

