Getting Weird Result with Map

Someone should, please explain why i am getting this [object Object] in the console where i used the template literal.

const person1 = { name: 'Sam' };
const person2 = { name: 'Sanchez' };
const myMap = new Map([[person1, {20: 'name'}]]);

myMap.set(person2, {age: 20}).set('General', {age: 30});
// myMap.forEach((value, key, map) => key === person1 ? console.log('found'): console.log(1));

for (const [key, value] of myMap.entries()) { // Array destructuring 
  console.log(key);  // returns the actual key
  console.log(`${key}`); // returns [object Object]
}

maybe it is because of the regular expression . dollar sign means: Matches the end of the string, or the end of a line if the multiline flag ( m ) is enabled. This matches a position, not a character.
Which lesson is this?

1 Like

@anon58011934 There is no regular expression use here.

@samolex The reason you see [object Object] is because in the first entry, person1 is an object. When you use the template literal, anything inside it becomes a string. JavaScript see the object and just displays the datatype instead of a property name value found inside the object. You could do the following to get the name.

console.log(`${key.name}`);
2 Likes