PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, August 13, 2022

[FIXED] how to get the following output of the code snippet?

 August 13, 2022     javascript, object, output     No comments   

Issue

I have been asked this question in an interview. How to solve this? The object and consoles statements are mentioned. I am not getting how to implement the function findPath? Code snippet


Solution

class Obj {
  constructor() {
    this.data = {
      a: {
        b: {
          c: 12
        }
      }
    };
  }

  findPath = (str) => {
    let sol = this.data;
    for (let key of str.split(".")) {
      sol = sol[key];
      if (!sol) {
        return undefined;
      }
    }
    return JSON.stringify(sol);
  };
}

let obj = new Obj();
console.log(obj.findPath("a.b.c"));
console.log(obj.findPath("a.b"));
console.log(obj.findPath("a.b.d"));
console.log(obj.findPath("a.c"));
console.log(obj.findPath("a.b.c.d"));
console.log(obj.findPath("a.b.c.d.e"));



Answered By - Ketan Ramteke
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing