Reputation: 678
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?
Upvotes: 1
Views: 773
Reputation: 2069
A simple approach
const obj = {
a: {
b: {
c: 12,
},
},
k: null,
};
const testFunc = (obj, k) => {
const arr = k.split(".");
for (let i = 0; i < arr.length; i++) {
obj = obj[arr[i]];
}
return obj;
};
console.log(testFunc(obj, "k")); //null
console.log(testFunc(obj, "a.b.c")); //12
console.log(testFunc(obj, "a.b.c.d")); //undefined
console.log(testFunc(obj, "f")); //undefined
Upvotes: 0
Reputation: 312
This could do it
var obj = {
a: {
b: {
c: 1
}
}
}
function findPath(path) {
const paths = path.split('.');
let innerObj = {...obj};
for (let i = 0; i < paths.length; i++) {
innerObj = innerObj && innerObj[paths[i]] || null;
}
return innerObj;
}
console.log(findPath("a.b.c"));
console.log(findPath("a.b"));
console.log(findPath("a.b.d"));
console.log(findPath("a.c"));
console.log(findPath("a.b.c.d"));
console.log(findPath("a.b.c.d.e"));
Upvotes: 0
Reputation: 10655
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"));
Upvotes: 3
Reputation: 10382
var obj = {
a: {
b: {
c: 1
}
}
}
obj.findPath = function(path) {
const keys = path.split('.');
return keys.reduce((currentPath, key) => {
return currentPath && currentPath[key]
}, this)
}
console.log(obj.findPath('a'))
console.log(obj.findPath('a.b'))
console.log(obj.findPath('a.b.c'))
console.log(obj.findPath('a.b.c.d'))
Upvotes: 3