Skip to content

Instantly share code, notes, and snippets.

@deepak-terse
Last active March 25, 2021 15:51
Show Gist options
  • Save deepak-terse/d41cedcb4eaafb24224227e3e58701db to your computer and use it in GitHub Desktop.
Save deepak-terse/d41cedcb4eaafb24224227e3e58701db to your computer and use it in GitHub Desktop.
Object Traversal
/*
Problem Statement:
- To write a function 'findPath' which will traverse through the object 'obj' and print the output based on the path specified
- The sample I/P and O/P is given below in the console statement
*/
var obj = {
a: {
b: {
c: 12
}
},
findPath: function(path){
var nodesArray = path.split('.')
var objCopy = obj;
nodesArray.forEach((e) => {
try {
objCopy = objCopy[e];
} catch {
objCopy = undefined;
}
});
return objCopy;
}
};
console.log(obj.findPath('a.b.c')); // 12
console.log(obj.findPath('a.b')); // {c: 12}
console.log(obj.findPath('a.b.d')); // undefined
console.log(obj.findPath('a.c')); // undefined
console.log(obj.findPath('a.b.c.d')); // undefined
console.log(obj.findPath('a.b.c.d.e')); // undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment