0

Given a JS Object:

var obj = {
            a: {
               b: {
                  c: {}
               }
            }
         };

How can i convert obj.a.b into string "obj.a.b" to count how many objects (3) have been used? In this case obj.a.b: 3. I have tried ''+obj.a.b, uneval(), toSource(), toString(), for...in, Object.key().length but it is not what i want to know. I imagine it's not possible... but not sure.

For example why i want:

function h (o) {
    let a = o.split('.');
    if (a.length > 2) {
        alert('not allowed'); // because obj.a.b > 2
        return;
    } else {
        // because obj.a == 2 -> ok. process with obj.a ..
    }
}

h(obj.a.b);
hg95
  • 1
  • 2
  • 1
    So you want to be able to type `obj.a.b` and get back `"obj.a.b"`? – Mike Cluck Sep 07 '16 at 20:07
  • `obj.a.b` what do you mean by that? Do you have some code that accesses that? Do you just want to find how many levels deep `b` is? Where does that come from and also, why do you want to count references? – VLAZ Sep 07 '16 at 20:07
  • @Mike: Yes, exactly – hg95 Sep 07 '16 at 20:11
  • This looks like an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – Titus Sep 07 '16 at 20:13
  • @Vld: no, i dont want to find the levels deep of `b` or the source of `obj.a.b` like `JSON.stringify()` etc... – hg95 Sep 07 '16 at 20:14
  • 2
    @hg95 OK, but _why_ do you want to do that? Just curiosity or are you trying to solve something? Because if it's the latter, it does indeed seem like an XY problem. – VLAZ Sep 07 '16 at 20:14
  • you can use something like JSON.stringify(obj).replace(/\}|\{|'/gi, ''); then replace the ": to . and u will get what you want – Vural Sep 07 '16 at 20:21
  • 1
    You could do some crazy shenanigans with [Proxies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/get) to get at least each property access but it would definitely be some shenanigans. Not something you'd want for real-world code. – Mike Cluck Sep 07 '16 at 20:22
  • @Vld: i have updated with example – hg95 Sep 07 '16 at 20:41
  • Doesn't explain why exactly you want to do that. It's possible to do it. The ways range from a bit off to a bit unwieldy but overall doable. Avoiding it would be vastly easier, though and it sounds to me like you are trying to solve something in a roundabout way, perhaps there is a better solution. – VLAZ Sep 07 '16 at 20:45

1 Answers1

-2

A solution on how to find the depth of an object has already been provided under How to check the depth of an object?.

If you just need to convert it to a string form you could

> JSON.stringify(obj)
"{"a":{"b":{"c":{}}}}"
Community
  • 1
  • 1
  • Again, I don't think OP is looking for the _total depth_ of the object nesting but check how many levels deep _specifically_ a particular value retrieval is. – VLAZ Sep 07 '16 at 20:23