How to control property enumeration (for...in) with Proxy objects?
Unfortunately, it isn't possible to do this anymore.
As Brian Terlson (the editor of the EcmaScript Specification) wrote:
issue with proxy enumerate trap and for-in, where iimplementations are prevented from pre-populating the list of keys in the object, because the iterator causes observable affects. Which means the iterate must be pulled for every iteration. Last meeting we thought it would be ok if the enumerate trap exhausts the iterator, we thought that would solve the problem. The issue was, now their is an observable difference between an object and proxy of that object, mainly due to delete.
(Source: https://github.com/rwaldron/tc39-notes/blob/master/es7/2016-01/2016-01-28.md#5xix-proxy-enumerate---revisit-decision-to-exhaust-iterator via https://ecmascript-daily.github.io/2016/02/10/why-remove-enumerate-and-reflect-enumerate)
So it was removed due to technical challenges that could not be solved in a satisfactory manner.
has proxy trap
The in
operator as such can still be captured using the has
proxy trap:
var p = new Proxy({}, {
has: function(target, prop) {
if (prop === 'a') { return true; }
return false;
}
});
'a' in p; // true
'b' in p; // false
Alternative
As for (let key in proxy)
loops are more of a legacy feature these days, you could use one of the following with the ownKeys
proxy trap:
Object.keys()
(own enumerable properties only)Object.getOwnPropertyNames()
(own properties)Reflect.ownKeys()
(own properties and Symbols)
(Source: https://twitter.com/nilssolanki/status/659839340592422912)
(but you probably already knew that, seeing that you are working with proxies in the first place)
user2106769 gave the solution as a comment, but for anyone else like me who didn't see their comment, you can override for..in
iteration with ownKeys
and getOwnPropertyDescriptor
:
var obj = { "hello": "world" };
var proxy = new Proxy(obj, {
ownKeys: function() {
return ["a", "b"];
},
getOwnPropertyDescriptor: function(target, key) {
return { enumerable: true, configurable: true, value: this[key] };
}
});
for (var key in proxy) {
console.log(key);
}
EDIT: As Pärt Johanson mentioned, for correctness, "value" should be returned by getOwnPropertyDescriptor.