Created
November 16, 2011 17:46
-
-
Save piscis/1370790 to your computer and use it in GitHub Desktop.
Walk a javascript hash recursive and check for key exists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var a = { a: { b: 1 } }; | |
var b = ['a','b']; | |
var hashKeyExists = function(obj,path){ | |
var keys = path.split('.'); | |
var keyExists = function(obj,keyList){ | |
var cur = keyList.shift(); | |
if(obj.hasOwnProperty(cur)){ | |
if(keyList.length<=0){ | |
return true; | |
}else{ | |
return keyExists(obj[cur],keyList); | |
} | |
}else{ | |
return false; | |
} | |
}; | |
if(obj && typeof obj == "object" && keys.length>0){ | |
return keyExists(obj,keys); | |
}else{ | |
return false; | |
} | |
} | |
// Test cases - for chrome console | |
assert(hashKeyExists(a,'a.b')==true,'the key´s should exist'); | |
assert(hashKeyExists(a,'a.b.')==false,'the key should not exist'); | |
assert(hashKeyExists(a,'a')==true,'the key should exist'); | |
assert(hashKeyExists(a,'a.b.c')==false,'the key should not exist'); | |
assert(hashKeyExists(null,'a.b.c')==false,'return value should be false not a valid has'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment