Reputation: 37
I'm trying to create a map of objects to use by the following code:
var MARKED ={className: 'emoji', img:'⚐'} ;
var EMOJI_WONDER = {className: 'emoji', img: '🙄'};
var EMOJI_WIN = {className: 'emoji', img: '😁'};
var emoMap={};
emoMap[EMOJI_WONDER]=EMOJI_WONDER;
emoMap[MARKED]=MARKED;
emoMap[EMOJI_WIN]=EMOJI_WIN;
console.log(emoMap);
and i get object object. I've made a map before with the following code:
var str = 'this is a test la la la la lo';
var wordMap = countWordApperances(str);
console.log(str, 'got: ', wordMap);
function countWordApperances(txt) {
var wordCountMap = {};
var words = txt.split(' ');
for (var i = 0; i < words.length; i++) {
var currWord = words[i];
if (wordCountMap[currWord]) wordCountMap[currWord]++;
else wordCountMap[currWord] = 1;
}
return wordCountMap;
}
and i just can't tell why the top code won't set a map and the bottom code does.
Upvotes: 0
Views: 539
Reputation: 2236
What is happening in top case is that :
.toString()
gets called and on MARKED
, EMOJI_WONDER
and EMOJI_WIN
before using it as a key. Therefore, all assignments get loaded upon the same key. Viz: '[object Object]'
.
Hence, when you print the output is:
{
'[object Object]': {
className: 'emoji',
img: '😁'
}
}
The final assignment (EMOJI_WIN
)
Upvotes: 0
Reputation: 1073968
When you do this:
emoMap[EMOJI_WONDER]=EMOJI_WONDER;
you're using EMOJI_WONDER
as both the key (name) of the property and its value. Property names can only be strings or Symbols, they cannot be objects. So when you do that, EMOJI_WONDER
is coerced to string to form a property name. Since all of your objects are plain objects, they all coerce to the same string: "[object Object]"
. That's why your emoMap
ends up with only one property.
Perhaps you meant to use the variable names as the property names:
emoMap.EMOJI_WONDER = EMOJI_WONDER;
// or
emoMap["EMOJI_WONDER"] = EMOJI_WONDER;
If not, you probably want an array or Set
.
Upvotes: 3
Reputation: 13506
You have pass a variable object as a key for the object emoMap
,you need to use string as key instead
var MARKED ={className: 'emoji', img:'⚐'} ;
var EMOJI_WONDER = {className: 'emoji', img: '🙄'};
var EMOJI_WIN = {className: 'emoji', img: '😁'};
var emoMap={};
emoMap["EMOJI_WONDER"]=EMOJI_WONDER;//add quote to make it work
emoMap["MARKED"]=MARKED;
emoMap["EMOJI_WIN"]=EMOJI_WIN;
console.log(emoMap);
Upvotes: 2