0

I have a javascript object which is built dynamically in a loop. I'd like to replace properties that might already exist with newer ones during the iteration- basically treating the object like a Java HashSet.

Why is it that when you add a dynamic property to a javascript object, and later loop over that object with a for in loop, you get the multiple values of that property or other strange behavior?

Example:

var foo = {};

foo['bar'] = 'hello';

foo['bar'] = 'hola';

foo['bar'] = 'aloha';

foo['baz'] = 'some other thing';

var arr = [];

for(var prop in foo) { arr.push(foo[prop]) };
//2 entries (what I'd expect)

foo['bam'] = 'other other thing';

for(var prop in foo) { arr.push(foo[prop]) };
//5 entries (why?) the [bar] property should be overwritten right?

console.log(arr);
[ 'aloha',
  'some other thing',
  'aloha',
  'some other thing',
  'other other thing' ]

How does one overwrite the old value with a new one using dynamic properties?

2
  • You wrote bam, not bar, so bar won't be modified. Commented Jul 2, 2013 at 3:44
  • Those extra properties were there on purpose, but Ehtan's answer below highlights the real problem, which is that it works as expected, but I pulled noob move! Commented Jul 2, 2013 at 3:49

2 Answers 2

4

Object properties are working the way you expect them to. The problem is you're not clearing the arr array; so you're just piling the same properties onto it. Try putting arr = []; before your second for loop, and you should be golden.

You can use objects like a hash; if, instead, you had this:

var hash = {};
for( var prop in foo ) { hash[prop] = foo[prop]; }

You will get the behavior you want, even if you re-use the hash variable. Arrays are NOT like objects.

Sign up to request clarification or add additional context in comments.

2 Comments

Ridiculous, I've been staring at this for too long, my code (not shown) has the array in the wrong place)... Sigh. Thanks for answering...
Heh. We all have days like that, @binarygiant. On the good days, we don't make fools of ourselves on SO. On the bad days, well...it's a forgiving lot!
1

you never cleared the array after the first loop. so you add the 'bar' and 'baz' to the array, then add 'bam' to foo, loop through foo again and get 'bar', 'baz' (from first iteration), then 'bar', 'baz', and 'bam' (from second iteration)

Comments

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.