0

Javascript Object.keys(my_obj) return the keys (ie enumerable property) of my_obj in an array.

But looping in Object.keys(my_obj) array return the methods of my_obj.

Does somebody understand this behaviour ?

Object.prototype.log_key = function() {
  keys = Object.keys(this)
  console.log('log Object.keys() array return enumerable property', keys)
  for (const k in keys) {
    console.log('loop in Object.keys() array return method', k)
  }
}

var my_obj = {
  testkey: 'testvalue'
}

my_obj.log_key();

Output:

log Object.keys() array return enumerable property [ 'testkey' ]
loop in Object.keys() array return methods 0
loop in Object.keys() array return methods log_key
Barmar
  • 741,623
  • 53
  • 500
  • 612
G.S
  • 392
  • 2
  • 13
  • 1
    `for ... in` includes inherited properties. – Barmar Mar 22 '20 at 22:14
  • `keys` is an array, the `0` is the element with value `testkey` ... the `testkey` property is the enumerable property (method) you've added to every object, including the `keys` array - that's not the `log_key` of `my_obj`, it's the `log_key` of `keys` that is being enumerated – Jaromanda X Mar 22 '20 at 22:22
  • 2
    To be clear, [*for..in*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) returns all the object's property names, both on the object and it's inheritance chain, not the values. So what you're seeing are the properties of the array returned by [*Object.keys*](http://ecma-international.org/ecma-262/10.0/#sec-object.keys), not the properties of the object passed to *Object.keys*. – RobG Mar 22 '20 at 22:26

1 Answers1

0

for...in loops give you the index of the array. That's why you're getting 0 when you log k. It's the first and only item in the array.

If you want the actual item you can use a for...of instead.

cd3k
  • 719
  • 5
  • 8