3 回答

TA貢獻1780條經(jīng)驗 獲得超4個贊
一種方法是使用遞歸搜索函數(shù)doesObjectHaveNestedKey(),如下所示(這不需要額外的依賴,如lodash):
const object = {
some : {
nested : {
property : {
to : [
{
find : {
foo : [ 1 , 2 , 3 ]
}
}
]
}
}
}
}
/* Define function to recursively search for existence of key in obj */
function doesObjectHaveNestedKey(obj, key) {
for(const k of Object.keys(obj)) {
if(k === key) {
/* Search keys of obj for match and return true if match found */
return true
}
else {
const val = obj[k];
/* If k not a match, try to search it's value. We can search through
object value types, seeing they are capable of containing
objects with keys that might be a match */
if(typeof val === 'object') {
/* Recursivly search for nested key match in nested val */
if(doesObjectHaveNestedKey(val, key) === true) {
return true;
}
}
}
}
return false;
}
console.log('has foo?', doesObjectHaveNestedKey(object, 'foo') ) // True
console.log('has bar?', doesObjectHaveNestedKey(object, 'bar') ) // False
console.log('has nested?', doesObjectHaveNestedKey(object, 'nested') ) // True
這里的想法是:
通過輸入對象“obj”的鍵查找與輸入“key”匹配的鍵“k”
如果找到匹配則返回true,否則返回true
查找能夠存儲嵌套對象的“obj”的任何值“val”(探索“對象”類型,因為只有這些可以存儲嵌套鍵)和
以遞歸方式搜索這些類型的“val”以獲得匹配,如果找到,則返回true

TA貢獻1828條經(jīng)驗 獲得超3個贊
Dacre Denny的答案也可以寫成:
const hasKey = (obj, key) => Object.keys(obj).includes(key) || Object.values(obj) .filter(it => typeof it === "object") .some(it => hasKey(it, key));
添加回答
舉報