最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Map has duplicate keys - Stack Overflow

programmeradmin1浏览0评论

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);          
    });
}
发布评论

评论列表(0)

  1. 暂无评论