1

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.

3
  • 1
    Only origObj is proxied, the inner objects are not. Commented Aug 31, 2017 at 6:35
  • Yes, I know that's why I asked how can I do that for nested object (sry for my english). Commented Aug 31, 2017 at 7:01
  • If you don't want to create proxies recursively, you need to traverse the target inside the proxy. Commented Aug 31, 2017 at 8:43

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

This doesn't work because it logs all steps not just the last one.
@MatejMazur What do you mean by "just the last one"? I thought you wanted each of the three Object.keys calls to trigger the log.
I've updated my question with the screenshot of the console where it's visible the output.
@MatejMazur Ah, I see now. That seems to be a problem with your console - the console.log itself does enumerate the contents of the logged object, triggering its trap again. Try in another environment or with a different callback function. (It shows as expected in Chrome devtools for example)
I see! Interesting.. thanks for the clarification! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.