I'm working on an ExtJS webapp and was looking for a way to list all of an object's own property names. Googling around, I quickly found some reference code on this blog. Now, when using this keys() method, I find some strange behavior when enumerating the property names of an object of objects. Example code:
keys = function(obj) {
if (typeof obj != "object" && typeof obj != "function" || obj == null) {
throw TypeError("Object.keys called on non-object");
}
var keys = [];
for (var p in obj)
obj.hasOwnProperty(p) && keys.push(p);
return keys;
};
var test = {}
test["nr1"] = {testid: 1, teststr: "one"};
test["nr2"] = {testid: 2, teststr: "two"};
test["nr3"] = {testid: 3, teststr: "three"};
for (var i in keys(test)) {
console.log(i);
}
When running this code, the console outputs:
0
1
2
remove()
So, on top of the expected 3 property names, it also lists a "remove()" function. This is clearly related to ExtJS, because the enumeration works as expected on a blank, non-ExtJS loading page.
Can anyone explain me what exactly ExtJS is doing here? Is there a better way to enumerate object-own property names?
Thanks a bunch, wwwald
There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.
For getting all of the keys of an Object you can use Object. keys() . Object. keys() takes an object as an argument and returns an array of all the keys.
Using hasOwnProperty() function The function hasOwnProperty() will check for the existence of a key in the given object and returns true if the key is present or else it returns false. This function takes the key of the object as the parameter and returns the Boolean result accordingly.
Try to check hasOwnProperty
to only list properties of the array itself, not its prototype.
for (var i in keys(test)) {
if(keys(test).hasOwnProperty(i)){
console.log(i);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With