Problem Statement:
- Write method findPath
- Should take two params:
- object
- keys separated by dots as string
- Return value if it exists at that path inside the object, else return undefined
My Approach:
- Initialise answerObject as the original Object.
- Split the string with
.
. - Traverse the spitted array.
- Update answerObject with the value read from iterated key.
- If answerObject is not undefined, then continue.
- Else break.
- Return answerObject.
CODE:
var obj = {
a: {
b: {
c: 12,
j: false
},
k: null
}
};
function findPath(obj, str=''){
var ansObj = JSON.parse(JSON.stringify(obj));
var attributes = str.split('.');
if(!attributes.length){
return undefined;
}
let index = 0;
while(attributes[index]){
if(ansObj[attributes[index]]!== undefined){
ansObj = ansObj[attributes[index]];
} else {
ansObj = undefined;
break;
}
index++;
}
return ansObj;
}
//Output:
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
Let's discuss your approach in the discussion box or you can hit me up at aastha.talwaria29@gmail.com.
Thanks for reading.
Top comments (4)
I shortened it a little bit :D
Or alternatively:
I don't understand why you need that.
a simple:
gives the same result.
When you are dealing with data where the contents may vary and you don't want to necessarily run into
Uncaught TypeError: Cannot read properties of undefined
If the path is fixed at design time in modern JavaScript you can use the Optional chaining (?.) and Nullish coalescing operator (??) operator to avoid errors.
When the
path
is generated at runtime. lodash supports this functionality with result and get.obj.a.b.c
can only be specified at design time - i.e. when you write the code. Dealing with "self-describing data" it is sometimes necessary to formulate apath
programmatically at runtime and then access (and/or mutate) it.Yes, but I guess it is more like a challenge.