How can I find a key in a JavaScript object when its depth is unknown?

If I have a javascript object like this: {a : { b: { c: { ... }}}} , how can I find if there is a key "x" in the object and what does it value?

+4
source share
2 answers

As long as they are not afraid of circular references, you can do the following

 function findX(obj) { var val = obj['x']; if (val !== undefined) { return val; } for (var name in obj) { var result = findX(obj[name]); if (result !== undefined) { return result; } } return undefined; } 

Note. This will search for the “x” property directly in this object or prototype chain. If you specifically want to limit the search to this object, you can do the following:

 if (obj.hasOwnProperty('x')) { return obj['x']; } 

And repeat for findX recursive call findX

+8
source
 function hasKey(obj,key){ if(key in obj) return true; for(var i in obj) if(hasKey(obj[i],key)) return true; return false; } 

Example:

 alert(hasKey({a:{b:{c:{d:{e:{f:{g:{h:{i:{}}}}}}}}}},'i')); 
+3
source

All Articles