6

I'm trying to send a Set() object via socket.io from node.js server. But from client side I'm getting an empty object.

//server side
var set=new Set([1,2,3]);
socket.emit('set', set);
console.log(set); //Set(3) {1,2,3}
//client side
socket.on('set',function(set){
  console.log(set); //{}
});

Why is that ?

0

1 Answer 1

6

From the docs:

All serializable datastructures are supported, including Buffer.

Set is not serializable (try doing JSON.stringify(new Set([1, 2, 3])). However, Array is serializable and you can convert a set into an array with a spread operator:

const s = new Set([1,2,3]);
socket.emit('set', [...s]);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for the answer. Are there any performance difference between [...s] & Array.from(s)
@Chamod It all depends on your environment - are you running natively or are you transpiling into ES5? Also, in most scenarios differences are going to be negligible. Have a look at Array.from() vs spread syntax

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.