Is there any way in Javascript to instantly access an object value with a specific depth?
There is an example:
{
"level": {
"value": "one",
"level": {
"value": "two",
"level": {
"value": "three",
"level": {
"value": "four",
"level": {
"value": "five"
}
}
}
}
}
}
I can do that with recursion. Check the first object value level
and if it exists then go to the next and when depth is what I need, I need to stop. And if depth is not reached and the next level
value does not exist, then raise some error.
Maybe there is some other way and approach to doing that?
CodePudding user response:
Depending on the depth of the object, you might get a stack overflow. To be extra cautious, I'd just use a while-loop.
You could write a function to loop over the object every time you want to get the value at a depth. This is fine if you're running it once, however, this is inefficient if you need to call it multiple times because the time complexity is O(n).
Instead, I would flatten the object so you have a sort of look-up array. The flatten function's time complexity is O(n), but every subsequent lookup is O(1). Take a look at this code:
function flatDepth(obj) {
let res = [];
while(typeof obj === 'object') {
res.push(obj.value);
obj = obj.level;
}
return res;
}
const obj = {
"level": {
"value": "one",
"level": {
"value": "two",
"level": {
"value": "three",
"level": {
"value": "four",
"level": {
"value": "five"
}
}
}
}
}
}
const flattened = flatDepth(obj);
console.log(flattened);
console.log(flattened[3]); // => 3
console.log(flattened[0]); // => undefined
console.log(flattened[5]); // => undefined