1) I am trying to add a sequence of key-value pairs to a JS plain object, where the key itself is an object. Each time I add a key-value pair, the object is overwritten (see live here).
var x = {};
var y = {
'name': 'cat',
'note': 'lazy animal'
}
var yy = 'meow'
x[{
'name': 'dog',
'note': 'loyal animal'
}] = 'bhow'
x[y] = yy
for(var k in x) {
console.log(k);
console.log(x[k]);
}
Console Output:
"[object Object]"
"meow"
2) This (overwriting behavior) does not happen when the key is a string (see live here).
var x = {};
var y = 'cat'
var yy = 'meow'
x['dog'] = 'bhow'
x[y] = yy
for(var k in x) {
console.log(k);
console.log(x[k]);
}
Console Output:
"dog"
"bhow"
"cat"
"meow"
Would like to understand why this is happening?
I figured our some solutions by going through the other questions (here). But I am unable to grasp the concept here. Any guidance will be much appreciated.