views:

46

answers:

2

I am using array as an associative array of objects in which keys are ID number of objects in database. Quiet naturally- IDs are large numbers - so that means it is common to have array of length 10^4 with only 20 elements as valid real objects.

I want to send this data back to server but whatever plugins I had to convert js objects to JSON- I tried them all & they all produce a JSON string of length 10^4. So much data can't be sent back.

I need a way of converting associative array to JSON discarding undefined entries.
Any suggestions ?

EDIT: Example of what my array looks like : var myAssociativeArray = [undefined, undefined,undefined...., someobject, some other object ...,undefined, ... yet another....]

A: 

Reading your question, it looks are using an array. Here's one solution to get only the defined entries of the array (order not guaranteed).

Note that since it is a sparse array and can go upto 10000 for instance, it's better to only enumerate the properties and not actually loop from 0 to 9999, as most of them will be undefined anyways. So this is better for performance.

var definedEntries = {};

for(var prop in dataObject) {
    if(dataObject.hasOwnProperty(prop)) {
        definedEntries[prop] = dataObject[prop];
    }
}

Then send definedEntries to the server.

Anurag
A: 

It sounds like you have a regular array, but you're using it as if it were sparse (which it may or may not be internally). Here's how to use a replacer function that will convert to an object:

JSON.stringify(root, function(k,v) 
{ 
  if(v instanceof Array) 
  { 
    var o = {}; 
    for(var ind in v) 
    { 
      if(v.hasOwnProperty(ind)) 
      { 
        o[ind] = v[ind]; 
      }
    } 
    return o; 
  } 
  return v; 
}); 
Matthew Flaschen