MakeMyTrip | Arzooo | Interview Question
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.
Full Experience
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.
Interview Questions (1)
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 method findPath that 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 return undefined.
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