Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding object keys in Javascript

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

like image 594
wwwald Avatar asked May 13 '11 13:05

wwwald


People also ask

How do you check if a key exists in an object in JavaScript?

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.

How do you find the object key of an array?

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.

How do you check if a key is present in an array of objects JavaScript?

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.


1 Answers

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);
    }
}
like image 143
Rocket Hazmat Avatar answered Sep 24 '22 06:09

Rocket Hazmat