简体   繁体   English

我如何 JSON 只编码 Javascript object 的一部分?

[英]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.我正在编写一个 2D 重力模拟游戏,我正在尝试添加保存/加载功能。 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.每个行星都由一个 Body object 表示,其中包含行星的坐标、质量和运动矢量。 It also stores an array of the last 100 coordinates of the planet in order to draw the planet's trail on the screen.它还存储了行星最后 100 个坐标的数组,以便在屏幕上绘制行星的轨迹。

I want to use JSON.stringify() to serialize the planets array.我想使用 JSON.stringify() 来序列化行星数组。 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).我想保存每个行星的第一个属性(质量、位置、运动),但我不需要保存最后 100 个坐标(轨迹数组)。 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?我可以只对每个 object 的一部分进行字符串化吗? If not, can I remove that portion of the JSON string after it's been encoded?如果不是,我可以在编码后删除 JSON 字符串的那部分吗? Or should I move the coordinates elsewhere during the save process then copy them back into each planet once it's been saved?或者我应该在保存过程中将坐标移动到其他地方,然后在保存后将它们复制回每个星球?

In modern web browsers you can use Array#map .在现代网络浏览器中,您可以使用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.或者,相当于使用for循环。

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.它只会给你三个部分作为 json 字符串。

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() );

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.从长远来看,拥有这样的方法也会提高您的可维护性。

You can use second parameter of JSON.stringify ( replacer )您可以使用 JSON.stringify 的第二个参数( 替换器)

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM