Why isn't ownKeys Proxy trap working with Object.keys()? - javascript

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))
Is MDN wrong, or am I doing something wrong?

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

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))

Related

Why does the new key show different when we use Object.defineProperty() in javascript? [duplicate]

I was playing with below javascript code. Understanding of Object.defineProperty() and I am facing a strange issue with it. When I try to execute below code in the browser or in the VS code the output is not as expected whereas if I try to debug the code the output is correct
When I debug the code and evaluate the profile I can see the name & age property in the object
But at the time of output, it only shows the name property
//Code Snippet
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile, 'age', {
value: 23,
writable: true
})
console.log(profile)
console.log(profile.age)
Now expected output here should be
{name: "Barry Allen", age: 23}
23
but I get the output as.
Note that I am able to access the age property defined afterwards.
I am not sure why the console.log() is behaving this way.
{name: "Barry Allen"}
23
You should set enumerable to true. In Object.defineProperty its false by default. According to MDN.
enumerable
true if and only if this property shows up during enumeration of the properties on the corresponding object.
Defaults to false.
Non-enumerable means that property will not be shown in Object.keys() or for..in loop neither in console
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile , 'age', {
value: 23,
writable: true,
enumerable: true
})
console.log(profile)
console.log(profile.age)
All the properties and methods on prototype object of built-in classes are non-enumerable. Thats is the reason you can call them from instance but they don't appear while iterating.
To get all properties(including non-enumerable)Object​.get​OwnProperty​Names()
.
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile , 'age', {
value: 23,
writable: true,
enumerable: false
})
for(let key in profile) console.log(key) //only name will be displayed.
console.log(Object.getOwnPropertyNames(profile)) //You will se age too
By default, properties you define with defineProperty are not enumerable - this means that they will not show up when you iterate over their Object.keys (which is what the snippet console does). (Similarly, the length property of an array does not get displayed, because it's non-enumerable.)
See MDN:
enumerable
true if and only if this property shows up during enumeration of the properties on the corresponding object.
Defaults to false.
Make it enumerable instead:
//Code Snippet
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile, 'age', {
value: 23,
writable: true,
enumerable: true
})
console.log(profile)
console.log(profile.age)
The reason you can see the property in the logged image is that Chrome's console will show you non-enumerable properties as well - but the non-enumerable properties will be slightly greyed-out:
See how age is grey-ish, while name is not - this indicates that name is enumerable, and age is not.
Whenever you use".defineProperty" method of object. You should better define all the properties of the descriptor. Because if you don't define other property descriptor then it assumes default values for all of them which is false. So your console.log checks for all the enumerable : true properties and logs them.
//Code Snippet
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile, 'age', {
value: 23,
writable: true,
enumerable : true,
configurable : true
})
console.log(profile)
console.log(profile.age)

Vue/Vuex: Distinguish arrays from objects in Proxy objects

As stated here, reactive Vuex objects are returned as Proxy objects. This may not be a problem in most cases, but how do I determine if the Proxy originated from an array or object?
The Proxy is a transparent layer on top of the array/object, so you would not need to determine the Proxy's original source.
The variable itself should be treated as if the Proxy layer were not there. If it's a Proxy of an Array, treat the variable as an Array, and the same for Object. Run the following code snippet for examples.
const arr = [1,2,3]
const arrProxy = new Proxy(arr, {}) // value is identical to `arr`
console.log(arrProxy.map(x => x * 10)) // => [ 10, 20, 30 ]
console.log('isArray', Array.isArray(arrProxy)) // => true
const obj = { foo: true, bar: false }
const objProxy = new Proxy(obj, {}) // value is identical to `obj`
console.log(Object.keys(objProxy)) // => [ 'foo', 'bar' ]
console.log('objArray type:', typeof objProxy) // => object

What does the descriptor's default value mean in Object.defineProperty()?

according to MDN, when using Object.defineProperty(), its third argument is a descriptor with some optional keys, such as
configurable
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
Defaults to false.
enumerable
true if and only if this property shows up during enumeration of the properties on the corresponding object.
Defaults to false.
...
I'd like to ask what does the defaults to false above mean?
I think it means that if I don't specify that key's value, it will be set to the default value, which is false, but when I try it in Chrome, it turns out to be as follows:
Object.getOwnPropertyDescriptor(o, 'a')
> {value: "c", writable: false, enumerable: true, configurable: true}
Object.defineProperty(o, 'a', {'enumerable': false})
> {a: "c"}
Object.getOwnPropertyDescriptor(o, 'a')
> {value: "c", writable: false, enumerable: false, configurable: true}
Apparently my descriptor missed the key configurable, but this attribute was not set to false.
Thanks for your help!
Quoting the same MDN article:
When the property already exists, Object.defineProperty() attempts to modify the property according to the values in the descriptor and the object's current configuration.
Since o.a already exists, Object.defineProperty() modifies the property with provided descriptor instead of defining it from scratch. In this case it only overwrites the keys you provide.
You can see the defaults in action by defining a new property.
var o = {}
> undefined
Object.defineProperty(o, 'a', {})
> {a: undefined}
Object.getOwnPropertyDescriptor(o, 'a')
> {value: undefined, writable: false, enumerable: false, configurable: false}

Is there a benefit to use "hasOwnProperty()" when iterating through object keys in JavaScript

I'm trying to understand the goal of using hasOwnProperty() check when iterating through object keys. As I know, the iteration will be executed for every object property (not more, not less) in both cases: with hasOwnProperty() or without. For example, in code below results with hasOwnProperty() check and without are the same:
const obj = {
prop1: [],
prop2: {},
prop3: "",
prop4: 0,
prop5: null,
prop6: undefined
}
const resultWithHasOwnProperty = [];
const resultWithoutHasOwnProperty = [];
for(key in obj) {
if(obj.hasOwnProperty(key)) {
resultWithHasOwnProperty.push(obj[key])
}
}
for(key in obj) {
resultWithoutHasOwnProperty.push(obj[key])
}
console.log("Result WITH hasOwnProperty check: ", resultWithHasOwnProperty);
console.log("Result WITHOUT hasOwnProperty check: ", resultWithoutHasOwnProperty);
So my question is: why and when should we use hasOwnProperty() check?
I'll rephrase my question: without hasOwnProperty() check we will always iterate through all existing properties anyway?
Notice, this question is not really a duplicate.
The docs indicate that:
The hasOwnProperty() method returns a boolean indicating whether the
object has the specified property as own (not inherited) property.
The hasOwnProperty method ensure that the property you are checking is directly on an instance of an object but not inherited from its prototype chain. If you don't check, it will loop through every property on the prototype chain.
const obj = {
prop1: [],
prop2: {},
prop3: "",
prop4: 0,
prop5: null,
prop6: undefined
}
obj.prototype = {foo: 'bar'};
P/s: NOTE that:
JavaScript does not protect the property name hasOwnProperty; thus, if the possibility exists that an object might have a property with this name, it is necessary to use an external hasOwnProperty to get correct results:
var foo = {
hasOwnProperty: function() {
return false;
},
bar: 'Here be dragons'
};
foo.hasOwnProperty('bar'); // always returns false
So you need to use:
Object.prototype.hasOwnProperty.call(foo, 'bar');

Object.getOwnPropertyNames vs Object.keys

What's the difference between Object.getOwnPropertyNames and Object.keys in javascript? Also some examples would be appreciated.
There is a little difference. Object.getOwnPropertyNames(a) returns all own properties of the object a. Object.keys(a) returns all enumerable own properties. It means that if you define your object properties without making some of them enumerable: false these two methods will give you the same result.
It's easy to test:
var a = {};
Object.defineProperties(a, {
one: {enumerable: true, value: 1},
two: {enumerable: false, value: 2},
});
Object.keys(a); // ["one"]
Object.getOwnPropertyNames(a); // ["one", "two"]
If you define a property without providing property attributes descriptor (meaning you don't use Object.defineProperties), for example:
a.test = 21;
then such property becomes an enumerable automatically and both methods produce the same array.
Another difference is in case of array Object.getOwnPropertyNames method will return an extra property that is length.
var x = ["a", "b", "c", "d"];
Object.keys(x); //[ '0', '1', '2', '3' ]
Object.getOwnPropertyNames(x); //[ '0', '1', '2', '3', 'length' ]
Literal notation vs constructor when creating object. Here is something that got me.
const cat1 = {
eat() {},
sleep() {},
talk() {}
};
// here the methods will be part of the Cat Prototype
class Cat {
eat() {}
sleep() {}
talk() {}
}
const cat2 = new Cat()
Object.keys(cat1) // ["eat", "sleep", "talk"]
Object.keys(Object.getPrototypeOf(cat2)) // []
Object.getOwnPropertyNames(cat1) // ["eat", "sleep", "talk"]
Object.getOwnPropertyNames(Object.getPrototypeOf(cat2)) // ["eat", "sleep", "talk"]
cat1 // {eat: function, sleep: function, talk: function}
cat2 // Cat {}
// a partial of a function that is used to do some magic redeclaration of props
function foo(Obj) {
var propNames = Object.keys(Obj);
// I was missing this if
// if (propNames.length === 0) {
// propNames = Object.getOwnPropertyNames(Obj);
// }
for (var prop in propNames) {
var propName = propNames[prop];
APIObject[propName] = "reasign/redefine or sth";
}
}
So in my case the foo function didn't work if I gave it objects of the cat2 type.
There are other ways to create objects so there could be other kinks in there as well.
As was already explained, .keys doesn't return non-enumerable properties.
Regarding to examples, one of pitfall cases is an Error object: some of its properties are non-enumerable.
So while console.log(Object.keys(new Error('some msg'))) yields [],
console.log(Object.getOwnPropertyNames(new Error('some msg'))) yields ["stack", "message"]
console.log(Object.keys(new Error('some msg')));
console.log(Object.getOwnPropertyNames(new Error('some msg')));
Another difference is that (at least with nodejs) "getOwnPropertyNames" function does not guarantee keys order, that's why I usually use "keys" function :
Object.keys(o).forEach(function(k) {
if (!o.propertyIsEnumerable(k)) return;
// do something...
});

Categories

Resources