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

javascript - How to emit a Map object - Stack Overflow

programmeradmin4浏览0评论

In the server side I have something like this:

const users = new Map();
users.set('id', { name: 'name' });
// ...

// then I emit:
io.emit('user_change', users);

In the client side I have something like:

socket.on('user_change', users => {
    for (let user of users) {
        userlist.append(`<li>${user.name}</li>`);
    }
});

But users is empty ({}).

How do I emit a Map object?

In the server side I have something like this:

const users = new Map();
users.set('id', { name: 'name' });
// ...

// then I emit:
io.emit('user_change', users);

In the client side I have something like:

socket.on('user_change', users => {
    for (let user of users) {
        userlist.append(`<li>${user.name}</li>`);
    }
});

But users is empty ({}).

How do I emit a Map object?

Share Improve this question asked Nov 23, 2016 at 14:07 FabricioFabricio 7,93510 gold badges58 silver badges93 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 16

socket.io (or whatever transport mechanism) is probably using JSON as the serialization format. Unfortunately, Maps and Sets and other ES2015 datatypes cannot be JSON-encoded.

let m = new Map([['one', 1], ['ten', 10], ['hundred', 100]]);
console.log(JSON.stringify(m));
// "{}"

It’s very inelegant but I convert to an array-of-arrays on the server-side, transmit that, and recreate the map on the client:

let transitString = JSON.stringify(Array.from(m));
console.log(transitString)
// "[["one",1],["ten",10],["hundred",100]]"
var newMap = new Map(JSON.parse(transitString));
console.log(newMap)
// Map {"one" => 1, "ten" => 10, "hundred" => 100}

So in your case, I’d do io.emit('user_change', Array.from(users)); on the server, and on the client, change the for loop to consume a map: for (let user of (new Map(users))).

You can parse the Map object to an object array just like this:

const myMap = new Map([
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key3', 'value3']
]);

const mapToArray = [];

for (const [key, value] of myMap.entries()) {
  mapToArray.push({key: key, value: value});
}

console.log(mapToArray);

With this workaround you can have some funcionalities from map just using the array instance methods (filter, find, indexOf...)

发布评论

评论列表(0)

  1. 暂无评论