Skip to content

Instantly share code, notes, and snippets.

@jptcnde
Last active April 20, 2018 09:58
Show Gist options
  • Save jptcnde/528ba43dca60758fa7e3375ec0a0d027 to your computer and use it in GitHub Desktop.
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
/* 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