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