admin管理员组

文章数量:1344192

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

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
Share Improve this question asked Aug 24, 2016 at 10:41 anthonygoreanthonygore 4,9875 gold badges33 silver badges30 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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

本文标签: Javascript Map has duplicate keysStack Overflow