Search code examples
javascriptarraysprototypejsto-json

Adding fields to JS array


I've added a field "max" to the JS array prototype. I'm having trouble seeing this addition when I stringify the array. I've tried to overwrite the toJSON function but to no avail.

Array.prototype.max = 0;
Array.prototype.toJSON = function(){
    var o = this;
    o.max = this.max;
    return o;
};

var a = [1,2,3];
a.max = 10;

console.log(JSON.stringify(a));
//'[1,2,3]'

I'd like to avoid doing something like {array_field:a,max_field:max} and just use the array object - is this possible? What am I doing wrong?


Solution

  • You have a few options here, none of them will do exactly what you want.

    Since JSON arrays are strictly limited to integer keys[1], you can't send down the value of max directly.

    Your choices include:

    • Using an object instead of an array. You loose all of the array magic, but it might work better for you.
    • Send down meta-data outside your array, such as a configuration object that includes both max and your array values
    • Force the array to be max long before sending it down. JSON will encode unused array elements with null.
    • Use a custom serialzer/deserializer. You could even code things in JSONS + the extras. In reality, this pretty much turns out the same as the second option.

    [1] Unlike JavaScript Objects