Last active
June 18, 2016 17:53
-
-
Save wkronemeijer/6854622 to your computer and use it in GitHub Desktop.
key value paths for javascript
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
function getKeyValue(object, path, default_value){ | |
"use strict" | |
if (typeof object === 'undefined') { | |
return default_value; | |
} | |
let prop_cont_pair = path.split('.'); | |
let prop = prop_cont_pair[0]; | |
let cont = prop_cont_pair.slice(1).join('.'); | |
if (cont === '') { | |
let oprop = object[prop]; | |
if (typeof oprop === 'undefined') { | |
return default_value; | |
} else if ((typeof oprop === "object") && (typeof default_value === "object")) { | |
let result = default_value; | |
for (var x in oprop) result[x] = oprop[x]; | |
return result; | |
} else { | |
return object[prop] | |
}; | |
} else { | |
return getKeyValue(object[prop], cont, default_value) | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment