9

In the documentation of the Proxy ownKeys trap on MDN it states that it will intercept Object.keys() calls:

This trap can intercept these operations:

Object.getOwnPropertyNames()

Object.getOwnPropertySymbols()

Object.keys()

Reflect.ownKeys()

However, from my tests it doesn't seem to work with Object.keys:

const proxy = new Proxy({}, {
  ownKeys() {
    console.log("called")
    return ["a", "b", "c"]
  }
})

console.log(Object.keys(proxy))

console.log(Object.getOwnPropertyNames(proxy))

console.log(Reflect.ownKeys(proxy))

3 Answers 3

9

The reason is simple: Object.keys returns only properties with the enumerable flag. To check for it, it calls the internal method [[GetOwnProperty]] for every property to get its descriptor. And here, as there’s no property, its descriptor is empty, no enumerable flag, so it’s skipped.

For Object.keys to return a property, we need it to either exist in the object, with the enumerable flag, or we can intercept calls to [[GetOwnProperty]] (the trap getOwnPropertyDescriptor does it), and return a descriptor with enumerable: true.

Here’s an example of that:

let user = { };

user = new Proxy(user, {
  ownKeys(target) { // called once to get a list of properties
    return ['a', 'b', 'c'];
  },

  getOwnPropertyDescriptor(target, prop) { // called for every property
    return {
      enumerable: true,
      configurable: true
      /* ...other flags, probable "value:..." */
    };
  }

});

console.log( Object.keys(user) ); // ['a', 'b', 'c']

Source

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

Comments

2

Object.keys returns only the enumerable own properties of an object. Your proxy doesn't have such, or at least it doesn't report them in its getOwnPropertyDescriptor trap. It works with

const proxy = new Proxy({}, {
  ownKeys() {
    console.log("called ownKeys")
    return ["a", "b", "c"]
  },
  getOwnPropertyDescriptor(target, prop) {
    console.log(`called getOwnPropertyDescriptor(${prop})`);
    return { configurable: true, enumerable: true };
  } 
})

console.log(Object.keys(proxy))

console.log(Object.getOwnPropertyNames(proxy))

console.log(Reflect.ownKeys(proxy))

Comments

-2
const proxy = new Proxy({}, {
ownKeys: function () {
  console.log("called")
  return ["a", "b", "c"]
  }
 });

2 Comments

While possibly correct, a code-only answer helps the person who asked the question, it doesn't do them or future visitors any good. Please consider improving your answer.
my friend i test code and work's fine. what should i do to improve answer

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.