Justin
Justin

Reputation: 1939

How do I JSON encode only part of a Javascript object?

I'm writing a 2D gravity simulation game and I'm trying to add save/load functionality. In the game I store all of the current planets in an array. Each planet is represented by a Body object which contains the coordinates, mass, and motion vector of the planet. It also stores an array of the last 100 coordinates of the planet in order to draw the planet's trail on the screen.

I want to use JSON.stringify() to serialize the planets array. I'd like to save the first attributes of each planet (mass, location, motion) but I don't need to save the last 100 coordinates (the trail array). I don't want to completely delete the coordinates otherwise the trails will disappear from the screen. Can I stringify only a portion of each object? If not, can I remove that portion of the JSON string after it's been encoded? Or should I move the coordinates elsewhere during the save process then copy them back into each planet once it's been saved?

Upvotes: 1

Views: 1947

Answers (4)

You can use second parameter of JSON.stringify (replacer)

const planet = {
  name: "Pluto",
  lastCoords: [[0, 0], [1,1,]]
}

const json = JSON.stringify(planet, (key, value) => key === "lastCoords" ? undefined : value)
// json === {"name":"Pluto"}

Upvotes: 0

Alexander
Alexander

Reputation: 23537

In modern web browsers you can use Array#map.

var serialized = JSON.stringify(planets.map(function(planet){
  return { 
    mass: planet.mass,
    location: planet.location,
    motion: planet.motion
  };
}));

Or, the equivalent using a for loop.

Upvotes: 2

Roonaan
Roonaan

Reputation: 1066

The best would be to create both a serialization and deserialization method. This will allow you to create the most efficient storage format while still allowing you to reconstruct as much of the objects as you deem necessary. You can use export/import, save/restore, serialize/deserialize terminology, whichever you see fit. Having methods like this will increase you maintainability in the long run as well.

Upvotes: 0

bukart
bukart

Reputation: 4906

try it this way

var saved = JSON.stringify( {mass:body.mass,location:body.location,motion:body.motion} );

it shall give you just the three parts as a json string.

A bit more extended you could provide your body class such an export function. For example:

Bodyclass.export = function( toexport ) {
    if ( undefined === toexport || toexport.constructor != Array ) {
        var toexport = [ 'mass', 'location', 'motion' ];
    }
    var export = {};
    for ( var i = 0; i < toexport; i++) {
        export[ toexport[ i ] ] = this[ toexport[ i ] ];
    ]
}

var saved = JSON.stringify( body.export() );

Upvotes: 0

Related Questions