Last active
March 25, 2021 15:51
-
-
Save deepak-terse/d41cedcb4eaafb24224227e3e58701db to your computer and use it in GitHub Desktop.
Object Traversal
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
/* | |
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