0

I'm just curious, but how do I make an object that has infinite depth through arbitrary properties, in Javascript? It would be an interesting stuff.

console.log(a); // is an object
for(let depth = 1; ; depth++)
{
    const arbitrary_property_name = Math.random().toString(36);
    console.log(a = a[arbitrary_property_name]); // is also an object
}

2 Answers2

3

It could be done with Proxy.

let the_void = {};
the_void = new Proxy(the_void, {get: _ => the_void});

console.log(the_void); // Proxy {}
console.log(the_void.this); // Proxy {}
console.log(the_void.this.is); // Proxy {}
console.log(the_void.this.is.interesting); // Proxy {}
console.log(the_void.this.is.interesting.isn.t); // Proxy {}
console.log(the_void.this.is.interesting.isn.t.it); // Proxy {}
console.log(the_void.this.is.interesting.isn.t.it['?']); // Proxy {}
0

Example of recursive

var a = {};
var cur_level = 1;
function depth(obj,level = 0){
    if (cur_level == level) {
         return
    } else {
        obj.new_level = {};
        cur_level++;
        obj.val = Math.random(); //save some data
        return depth(obj.new_level,level); //make new level
    }
}
depth(a,100) // in this case if you using this declare u receive depth near 100 levels
//depth(a) -> in this case you will receive infinite depth of your obj
console.log(a)
AkeRyuu
  • 91
  • 6