In Javascript an array [] can have properties too, because it's an object. However if you send this object to server via ajax/socket.io, it's array content stays, but its properties get lost.
For example:
var arr = ['john','peter'];
arr.a = 1;
console.log(arr.a); // 1
After sending this object via ajax, what the server sees:
console.log(arr.a); // undefined
Does anyone know why? I'm using Node.JS for server btw, thanks!
As others have mentioned, JSON.stringify() doesn't serialize array properties, even if they aren't "inherited" from proto.
If you're using jquery, a quick fix is to just use $.extend({},arr) http://jsfiddle.net/15vn4shu/1/
If not, you can write a function to convert to an object easily:
function convertArrToObj(arr){
//assuming typeof arr === 'object', put in guards if needed
var obj = {};
for (var key in arr){
if (arr.hasOwnProperty(key))
obj[key]=arr[key];
}
return obj;
}
Personally, I'd just make an object with a property being the value of this array, add add to this parent object whatever you need. I'm not sure how feasible this is in your use case though (I'd have to see the code).
var toSend = {data:arr, customProp:'value'};
Easy, supported by all versions of js, doesn't require a framework, and no O(n) run through to do the conversion (arr is a pointer here... Which may be a gotcha, but it doesn't seem like it for your case).