Skip to content
Advertisement

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement