Reputation: 4014
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....]
Upvotes: 0
Views: 1055
Reputation: 284786
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;
});
Upvotes: 1
Reputation: 141869
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.
Upvotes: 0