0

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.

3 Answers 3

3

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.

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

Comments

2

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);

Comments

0

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)

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.