Javascript Map Has Duplicate Keys
The Map Object Set Method Is Meant to Add a New Key/Pair, or Update an Existing Key/Pair. See Docs. I've Been Struggling to Figure out How It Is That My Map...
The Map object set method is meant to add a new key/pair, or update an existing key/pair. See docs.
I've been struggling to figure out how it is that my Map has ended up with duplicate keys when I attempt to populate it with database results:
let users = new Map();
function loadUserByName(name) {
db.loadUser({ name }, (err, user) => {
users.set(user.id, user);
});
}
loadUser('george');
users.forEach( (item) => { console.log(item.key); } );
// Output:
// 57bbfcb47ff30b00db69ae87
loadUser('george');
users.forEach( (item) => { console.log(item.key); } );
// Output:
// 57bbfcb47ff30b00db69ae87
// 57bbfcb47ff30b00db69ae87
1 Answer
A Map can have an object as the key. And just because two objects output as the same string, does not mean they are the same object. The above code can be fixed by casting user.id as a string i.e.:
function loadUserByName(name) {
db.loadUser({ name }, (err, user) => {
users.set(String(user.id), user);
});
}