MakeMyTrip | Arzooo | Interview Question
- Posted
- 27 May 2022
Summary
This post shares a JavaScript interview question about creating a utility function findPath to retrieve values from a nested object based on a dot-separated key path, along with a detailed iterative solution.
How it went
During an interview for a software development role, I was presented with a coding challenge to implement a findPath utility function. This function was designed to safely access deeply nested properties within an object using a dot-separated string path, returning undefined if any part of the path did not exist. I then proceeded to implement the solution.
Questions asked (1)
- 01
Implement findPath Function for Nested Objects
Data Structures & Algorithms · Medium
A string will be passed as an argument, if there is an embedded key present in the object, return it else return undefined.
Problem Statement:
Write a methodfindPaththat should take two parameters:
-object: The source object.
-keys separated by dots as string: The path to the desired property.
Return the value if it exists at that path inside the object, else returnundefined.
Example Usage:var obj = { a: { b: { c: 12, j: false }, k: null } };console.log(findPath(obj, 'a.b.c')); // 12 console.log(findPath(obj, 'a.b')); // {c: 12, j: false} console.log(findPath(obj, 'a.b.d')); // undefined console.log(findPath(obj, 'a.c')); // undefined console.log(findPath(obj, 'a.b.c.d')); // undefined console.log(findPath(obj, 'a.b.c.d.e')); // undefined console.log(findPath(obj, 'a.b.j')); // false console.log(findPath(obj, 'a.b.j.k')); // undefined console.log(findPath(obj, 'a.k')); // null