0

I understand that Javascript objects are flexible enough that they can imitate the common hash array functionality (keys as strings, values as primitive types, able to loop by keys/values)...

I have this example and I can't figure out why it doesn't work:

var hash = {
 'a' : '',
 'b' : '',
 'c' : '',
}

One of those values gets initialized like so:

hash['a'] = 5;

Then I try to loop through them:

var keys = Object.keys(hash);
for(var i in keys){
  console.log(hash[i]);
}

The result is 3 'undefined'.

Why is this happening?

2 Answers 2

4

The problem you have is you're iterating over the keys of the Object.keys array (those keys are the integer 0, 1, 2...) and you try to get the property of hash using those integers.

You don't need Object.keys here :

for(var i in hash){
  console.log(hash[i]);
}

If you really want to use Object.keys, iterate over the elements of the array :

var keys = Object.keys(hash);
for(var i=0; i<keys.length; i++){
  console.log(hash[keys[i]]);
}

or

Object.keys(hash).forEach(function(i){
    console.log(hash[i]);
});
Sign up to request clarification or add additional context in comments.

12 Comments

That for..in is that smart, huh?
Object.keys is fine, but if you're iterating using for in then you ought to guard it with Object.hasOwnProperty(key). If some bozo has added to Object.prototype then hasOwnProperty will return true only for the keys you assign to the instance.
You can't and you shouldn't guard against bozos. Adding unnecessary hasOwnProperty is bad practice in my opinion. It shows you don't know when it's needed.
Its not really a protection against 'bozo's, but sometimes you only are interested in properties which are not shared or accessed via prototype chains. So either use Object.getOwnPropertyNames() or indeed check for .hasOwnProperty.
We're talking about an object used as a map and created as a literal, not about some random object.
|
1

The variable "keys" is not getting initialized with the key values because of what seems to be a conflict between the variable name "keys" and the function "keys."

However, if you initialize "keys" as a variable beforehand, and then run the code snippet then it works correct.

Also, if you rename the variable "keys" to anything else then also it works okay.

Below attached screenshot shows the re-enactment of these steps in Chrome Console.

JS Key conflict

1 Comment

Nice explanation and it's what I should've done in the first place to track down the error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.