Tabraiz Ali
Tabraiz Ali

Reputation: 677

object has an extra property while extracting keys from an object

Object.prototype.looper = function() {
  var result = [];
  for (var property in this)
    result.push(property);
  return result;
};

var test = {name: "tab", age: 5};
console.log(test.looper());

How to eliminate looper to get just the keys

["name", "age", "looper", looper: function]

Output Needed

 ["name", "age"]

Upvotes: 1

Views: 130

Answers (3)

Teemu
Teemu

Reputation: 23406

hasOwnProperty does the trick:

for (var property in this) {
    if (this.hasOwnProperty(property)) {
        result.push(property);
    }
}

for..in iterates all properties in the prototype chain, hence it's recommended to always use hasOwnProperty() check when iterating properties of an object, especially when using some libraries. This is also one reason, why for..in is not suitable to iterate arrays.

Upvotes: 1

godfrzero
godfrzero

Reputation: 2270

You can use the Object.keys method. This only gives you the enumerable keys, so you won't be getting the looper key.

// Enumerable keys as an array
Object.keys( objectName );

The Object.keys method is included in the latest browsers, and you can add it in older browser if it doesn't exist, as mentioned in the linked article.

Upvotes: 3

Aadit M Shah
Aadit M Shah

Reputation: 74234

There are two solutions. You could either use Object.keys which does the same thing your looper function does:

var test = {name: "tab", age: 5};
console.log(Object.keys(test));

The second way is to add an additional check hasOwnProperty to looper:

Object.prototype.looper = function() {
  var result = [];
  for (var property in this)
    if (this.hasOwnProperty(property))
      result.push(property);
  return result;
};

var test = {name: "tab", age: 5};
console.log(test.looper());

It's that simple. See the demos:

  1. http://jsfiddle.net/aaditmshah/bhZbk/
  2. http://jsfiddle.net/aaditmshah/bhZbk/1/

Upvotes: 2

Related Questions