Skip to content

Instantly share code, notes, and snippets.

@wkronemeijer
Last active June 18, 2016 17:53
Show Gist options
  • Save wkronemeijer/6854622 to your computer and use it in GitHub Desktop.
Save wkronemeijer/6854622 to your computer and use it in GitHub Desktop.
key value paths for javascript
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