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
1 Answer
Reset to default 8A 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
版权声明:本文标题:Javascript Map has duplicate keys - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743702922a2524626.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论