如何发射Map对象

时间:2022-07-04 19:37:28

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?

如何发出Map对象?

1 个解决方案

#1


2  

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.

socket.io(或任何传输机制)可能使用JSON作为序列化格式。遗憾的是,Maps and Sets和其他ES2015数据类型不能进行JSON编码。

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))).

所以在你的情况下,我会做io.emit('user_change',Array.from(users));在服务器上,在客户端上,更改for循环以使用map:for(允许(new Map(users))的用户)。

#1


2  

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.

socket.io(或任何传输机制)可能使用JSON作为序列化格式。遗憾的是,Maps and Sets和其他ES2015数据类型不能进行JSON编码。

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))).

所以在你的情况下,我会做io.emit('user_change',Array.from(users));在服务器上,在客户端上,更改for循环以使用map:for(允许(new Map(users))的用户)。