Skip to content

Instantly share code, notes, and snippets.

@cleure
Last active May 16, 2019 03:04
Show Gist options
  • Save cleure/bd33738c91b7a4862700db3ba50cd9b5 to your computer and use it in GitHub Desktop.
Save cleure/bd33738c91b7a4862700db3ba50cd9b5 to your computer and use it in GitHub Desktop.
Object / Array Traversal - Recursive Solution
// Recursive inline function
function get(obj, path = '') {
return (function _get(obj, parts) {
return (obj === undefined || parts.length === 0) ? obj : _get(obj[parts.shift()], parts);
})(obj, path.split('.'));
}
// Pure recursion
function get(obj, path = '') {
const parts = Array.isArray(path) ? path : path.split('.');
return (obj === undefined || parts.length === 0) ? obj : get(obj[parts.shift()], parts);
}
// "Tests"
console.log(get({a: {b: { c: 5 } } }, 'a')); // { b: {c: { 5 }} }
console.log(get({a: {b: { c: 5 } } }, 'a.b')); // { c: 5 }
console.log(get({a: {b: { c: 5 } } }, 'a.b.c')); // 5
console.log(get({a: {b: { c: 5 } } }, 'a.b.bad')); // undefined
console.log(get({a: {b: { c: [1, 2, { d: 'Yes!' }] } } }, 'a.b.c.0')); // 1
console.log(get({a: {b: { c: [1, 2, { d: 'Yes!' }] } } }, 'a.b.c.1')); // 2
console.log(get({a: {b: { c: [1, 2, { d: 'Yes!' }] } } }, 'a.b.c.2')); // { d: 'Yes!' }
console.log(get({a: {b: { c: [1, 2, { d: 'Yes!' }] } } }, 'a.b.c.2.d')); // 'Yes!'
console.log(get(undefined, undefined)); // undefined
console.log(get(undefined, 'a.b.c')); // undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment