Skip to content

Instantly share code, notes, and snippets.

@nojimage
Last active June 18, 2019 10:07
Show Gist options
  • Save nojimage/a0f2df9bc76285f397dc1537d1f3dd64 to your computer and use it in GitHub Desktop.
Save nojimage/a0f2df9bc76285f397dc1537d1f3dd64 to your computer and use it in GitHub Desktop.
function hash_get(key, haystack) {
const keys = key.split('.');
if (!Object.prototype.hasOwnProperty.call(haystack, keys[0])) {
return null;
}
const matched = haystack[keys[0]];
if (keys.length === 1) {
return matched;
}
return hash_get(keys.slice(1).join('.'), matched);
}
export default hash_get;
@nojimage
Copy link
Author

example:

data = {
    user: {name: 'foo bar', 'email': '[email protected]'},
    posts: [
        { id: 1, title: 'First Article'},
        { id: 2, title: 'Second Article'}
    ]
}
hash_get('user.name', data)
// -> 'foo bar'

hash_get('posts.1.title', data)
// -> 'Second Article'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment