Last active
April 20, 2018 09:58
-
-
Save jptcnde/528ba43dca60758fa7e3375ec0a0d027 to your computer and use it in GitHub Desktop.
Traverse object by Array as path, returns the value when search term exists
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
/* desc: | |
- get and traverse the value from an Object | |
- returns immediately if found value is an Array data type | |
params | |
node: Object | |
path: Array | |
usage: | |
var obj = { | |
name: 'john doe', | |
hobbies: { | |
'plying-basketball': { | |
console: ['ps4', 'xbox'], | |
shoes: ['jordan'] | |
}, | |
singing: { | |
artists: [ | |
'just bieber', | |
'm&m' | |
] | |
} | |
}, | |
parents: { | |
mother: 'Jane Doe' | |
} | |
} | |
traverseObjByPath(obj, ['hobbies', 'singing']) | |
output: { | |
singing: { | |
artists: [ | |
'just bieber', | |
'm&m' | |
] | |
} | |
} | |
traverseObjByPath(obj, ['parents', 'mother']) | |
// output: Jane Doe | |
*/ | |
function traverseObjByPath(node, path){ | |
if (({}).toString.call(node) === '[object Array]') { | |
return node; | |
} | |
var searchNode = path.shift(); | |
var result = node[searchNode]; | |
if (typeof result === 'undefined' || !path.length) { | |
return result; | |
} | |
return traverseObjByPath(result, path); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment