1

I get unexpected behavior when trying to load a hash using objects as keys; ie, when retrieving my data later the hash always refers to the last key used. I would expect this to be due to the behavior of closures, however, I thought that I have done what would be necessary to prevent this:

var hash = {};
var arry = [];
var list = [{val:"a"},{val:"b"},{val:"c"}];

var len  = list.length;

dump("load : \n");

for (var i=0;i<len;i++) {

  let pos = i;
  let obj = list[pos];
  hash[obj] = obj.val;
  arry.push(obj);
  dump("    "+obj.val+"    "+hash[obj]+"\n");
}

dump("retrieve : \n");

for (var i=0;i<len;i++) {

  let pos = i;
  let obj = list[pos];
  dump("    "+obj.val+"    "+arry[pos].val+"    "+hash[obj]+"\n");
}

output is:

load :
    a    a
    b    b
    c    c
retrieve :
    a    a    c
    b    b    c
    c    c    c

I have purposely gone overboard in trying to prevent this by raising the scope of the iteration objects using let, still I am apparently missing something. I would like to understand the reason behind this, and how to prevent it using Javascript.

2 Answers 2

6

Object keys in JavaScript can only be strings. This means that if you pass something that is not a string, it gets converted to a string. Since you're using objects that don't "override" Object.toString, they'll all have the same string representation (it's "[object Object]"), which is why the hash always refers to the last key used.

More here: Strange equality issue with Javascript object properties

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

Comments

0

To extend @Matt Ball answer:

You can use JSON.stringify to string objects.

var a = {};
a.b = 1;

JSON.stringify(a);
// '{"b": 1}'

Note: You can't stringify circular objects:

var a = {};
a.a = a;

JSON.stringify(a);
// TypeError: Converting circular structure to JSON

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.