Skip to content

Instantly share code, notes, and snippets.

@vitkarpov
Last active May 3, 2017 12:37
Show Gist options
  • Save vitkarpov/03ca92a7b811cb2730c1f490f7905a5e to your computer and use it in GitHub Desktop.
Save vitkarpov/03ca92a7b811cb2730c1f490f7905a5e to your computer and use it in GitHub Desktop.
/**
* @example
* // 1
* jpath('.foo.bar', { foo: { bar: 1 } });
*
* // null
* jpath('.foo.bar.baz', { foo: 2 })
*/
const jpath = (function() {
function recursiveSearch(fields, source) {
const next = source[fields.shift()];
if (fields.length) {
if (typeof next === "object") {
return recursiveSearch(fields, next);
}
return null;
}
return next;
}
return function(jpath, source) {
return recursiveSearch(jpath.split('.').filter(Boolean), source);
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment