Error sending array in node.js and socket.io

I am using socket.io version 0.8.4

I have welded my problem as follows. I have data looking like this:

data.prop1 = []; data.prop1.push("man"); data.prop2 = []; data.prop2["hey"] = "man"; 

I send data from the server to the client as follows:

 socket.emit("data", data); 

On the client side, I get the data as follows:

 socket.on("data", function(data){ console.log(data); }); 

Weird:

 data.prop1 = []; data.prop1.push("man"); // This data exists in the client side data object data.prop2 = []; data.prop2["hey"] = "man"; // This data does not exist. 

data.prop2 is just an empty array on the client side.

Is there a known bug in json serializing arrays of a form in prop2?

Thank you in advance

EDIT:

The issue is resolved using this workaround:

 data.prop1 = []; data.prop1.push("man"); data.prop2 = {}; // <= Object instead of array data.prop2["hey"] = "man"; 
+4
source share
2 answers

ECMA-262 near JSON.stringify :

The representation of arrays includes only elements between zero and array.length – 1 inclusive. Named properties are excluded from the string.

Arrays must have numeric property names. Therefore, when data.prop2 converted to JSON (which, I believe, sends socket.io data), it does not get the 'hey' property. If you want to use non-numeric property names, you should use objects instead of arrays:

 data.prop1 = []; data.prop1.push("man"); data.prop2 = {}; // Notice we're creating an object, not an array. data.prop2["hey"] = "man"; // Alternatively: data.prop2.hey = "man" 
+6
source

Unfortunately, Javascript is not really working.

Check out this article about halfway down. This explains the problem when you try to set data.prop2 ["hey"] = "man";

+1
source

Source: https://habr.com/ru/post/1391026/


All Articles