1

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!

5
  • What does console.log(arr); show? Also, do provide a SSCCE for reproducing the behaviour. Commented Aug 24, 2014 at 1:46
  • Assuming you're using json as the transport format, it does not serialize the properties other than the numeric indices. Commented Aug 24, 2014 at 1:46
  • @Musa, then is there a way to do so? Commented Aug 24, 2014 at 1:53
  • 1
    Don't use an array, use a regular object. Commented Aug 24, 2014 at 1:54
  • Use a proper data structure that makes sense. Commented Aug 24, 2014 at 2:26

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

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.