Proxy - handler.ownKeys() - nested object

515 views Asked by At

How can I handle all traps for ownKeys in a nested object?

I only know how to handle one level deep object:

function wrap(obj, fn) {
  var handler = {
    ownKeys(target) {
      fn(target)
      return target
    }
  }
  return new Proxy(obj, handler)
}

var origObj = {
  a: {
    b: {
     c: 0
    }
  }
}

var wrappedObj = wrap(origObj, console.log)

Object.keys(wrappedObj) // => actual = expected: { a: { b: { c: 0 } } }
Object.keys(wrappedObj.a) // => actual: not working, expected: { b: { c: 0 } }
Object.keys(wrappedObj.a.b) // => actual: not working, expected: { c: 0 }

edit 1:

If I try to wrap each inner object (from this answer) then it logs all steps not just the last one. By "all steps" I mean the inner process of the proxy which goes through the whole nested object so it fires fn(target) multiple times but I want to fire it only once.

Output in the console

edit 2:

So it looks that the problem is with the node environmnent (node version 8.1.4) where proxy looks broken. In the chrome console is everything ok.

1

There are 1 answers

5
Bergi On BEST ANSWER

You have to create a proxy for every single of the objects:

var wrappedObj = wrap({
  a: wrap({
    b: wrap({
     c: 0
    }, console.log)
  }, console.log)
}, console.log)

If you don't want to do that explicitly, you can of course also traverse the object using recursion to do the wrapping programmatically, or you do create the proxies dynamically on every property access via the get trap.