MakeMyTrip | Arzooo | Interview Question

Posted
27 May 2022
335 reads

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)

  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 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

Know someone preparing? Send it to them:WhatsAppLinkedInX

Interviewed at MakeMyTrip recently?

Write up your rounds while you still remember the questions. It helps the next person more than you would think.

Share your experience
Discussion 0

Questions for the author, or how your own interview compared.

Join the discussion

Sign in with Google to comment or ask the author a question.

No comments yet

Be the first to share your thoughts and start the discussion!