What is the best way to encode only a specific section of a JavaScript object into JSON format?

Currently, I am in the process of developing a 2D gravity simulation game and I am faced with the challenge of implementing save/load functionality. The game involves storing all current planets in an array format. Each planet is depicted by a Body object which includes essential details such as coordinates, mass, and motion vector. Additionally, it maintains a record of the last 100 coordinates to produce a visual trail on the screen.

My objective is to utilize JSON.stringify() for serializing the planets array. However, my intention is to exclude the storage of the last 100 coordinates (trail array) and solely focus on saving the fundamental attributes of each planet (mass, location, motion). Is there a method to stringify only a portion of each object? If not, should I explore the option of eliminating that segment from the encoded JSON string afterwards? Alternatively, would it be more efficient to transfer the coordinate data elsewhere during the saving process and reinstate it into each planet upon completion of the save operation?

Answer №1

For modern web browsers, utilizing Array#map is recommended.

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

Alternatively, you can achieve the same result using a for loop.

Answer №2

give this method a try

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

this will output the three parts as a json string.

To enhance this further, you can add an export function to your body class. For instance:

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

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

Answer №3

To optimize storage and reconstruction of objects, it is recommended to implement both serialization and deserialization methods. These functions can help create an efficient storage format and allow you to rebuild objects with the necessary data. You may choose to refer to these processes as export/import, save/restore, serialize/deserialize, or any other terminology that fits your project. By incorporating these methods, you can improve maintainability in the future.

Answer №4

To exclude certain properties from being included in the JSON string, you can utilize the second parameter of JSON.stringify called "replacer".

const star = {
  title: "Sirius",
  coordinates: [[10, 20], [30,40]]
}

const jsonData = JSON.stringify(star, (key, value) => key === "coordinates" ? null : value)
// jsonData will only contain {"title":"Sirius"}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updating the iFrame source using jQuery depending on the selection from a dropdown menu

I want to create a dynamic photosphere display within a div, where the source is determined by a selection from a drop-down menu. The select menu will provide options for different rooms that the user can view, and the div will contain an iframe to showca ...

What could be causing the issue with "class not being recognized as a constructor" error that I am encountering?

When attempting to create an instance from modules in routing, I consistently encountered the error message "class is not a constructor." Below is the code snippet: export class Modules{ modules : object = { masterdata : MasterdataModule, shop : ...

I'm encountering a problem with my vuejs application

I am currently working on a new vuejs 2 app and encountered an unexpected error. ERROR in ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0&bustCache!./src/components/Customers.vue Module build failed: S ...

What are the best practices for securely using JSON.stringify in JavaScript?

When I use JSON.stringify on a string that includes <script> tags, the script tags somehow escape and show up in the body of my document, causing unexpected results with the "injected" data. I'm puzzled by how they manage to escape, considering ...

Link property can be added to a bindpopup polygon in Leaflet to have it open in a new tab when clicked

Is it possible to include a hyperlink in popup content on Leaflet, similar to this example? function onEachFeature(feature, layer) { idLoDat = feature.properties.IDLo; layer.bindPopup("Company name: " + feature.properties.TenCty + " ...

The Power of Javascript in Enhancing Lightbox Experience

I am trying to enhance an image outputted by JavaScript with Lightbox functionality. Since the image link is dynamically created, I am approaching it this way! Despite searching on Stack Overflow, I have not found a solution that fits my needs... The cur ...

Assess JavaScript for Fetch API implementation

Currently, I am utilizing node.js on Windows with the express module to create an HTML page where I need to retrieve data from a server-side function called getfiledata() (I want to keep my Javascript and text file private). I have attempted to use fetch( ...

Troubles encountered when cascading val(), text(), and data()

Here is my JavaScript/jQuery code: $select.append($("<option />") .val(this.id) .text(this.text) .data('name', this.name) .data('isstorage', this.isstorage)); Although it successfully assigns values to t ...

Encountering memory leaks and displaying repetitive data due to having two distinct observables connected to the same Firestore

I am currently utilizing @angular/fire to retrieve data from firestore. I have two components - one serving as the parent and the other as the child. Both of these components are subscribing to different observables using async pipes, although they are bas ...

Implement the usage of plainToClass within the constructor function

I have a dilemma with my constructor that assigns properties to the instance: class BaseModel { constructor (args = {}) { for (let key in args) { this[key] = args[key] } } } class User extends BaseModel { name: str ...

What are the steps to create a dictionary app utilizing the Oxford Dictionary API?

The code snippet provided in the documentation returns a JSON result, but I am only interested in extracting the meaning of the word. Can someone guide me on how to specifically extract the meaning without fetching the entire JSON file? As a beginner in an ...

Is it advisable to implement the modular pattern when creating a Node.js module?

These days, it's quite common to utilize the modular pattern when coding in JavaScript for web development. However, I've noticed that nodejs modules distributed on npm often do not follow this approach. Is there a specific reason why nodejs diff ...

Encountered an ERESOLVE error when attempting to install a package, unable to resolve the dependency tree

After attempting to install the necessary dependencies for my project with npm install, an error message came up that I am unable to decipher: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: &l ...

Issue encountered when sorting sequelize query by date in ascending sequence

My challenge is to arrange a sequelize query in ascending order by date. Specifically, I am focusing on sorting the results of the model: ExamScore (referred to as student_score). I've specified the column "updated_at" for ordering and the method of ...

Create a new JSON array by filtering this JSON array based on a specific date range

Having a json array that contains the following keys and values: { "results": [ { "date": "2013-15-5", "position": "23", "race" : "2" }, { "date": "2013-15-6", "positio ...

RestKit JSON Object Mapping: A powerful tool for converting JSON objects

Below is a JSON response that I have received. How can I perform object mapping for this data? My platform of choice is iOS and I am utilizing RestKit. { "predictions":[ { "description":"User1", "id":"75b8c57b4443f4b ...

Determine the precise location of a screen element with jQuery

Can anyone help me determine the precise position of an element on the current visible screen using jQuery? My element has a relative position, so the offset() function only gives me the offset within the parent. Unfortunately, I have hierarchical divs, ...

What is the best way to invoke a function within an AngularJS controller?

Currently, I am exploring the most efficient method of calling a function from an AngularJS controller externally. In our setup, data is transmitted from a Python backend to the frontend using JavaScript functions. To feed this data into the Angular contr ...

What is the best way to send two Array objects through http requests in AngularJS?

Is there a way to receive two parameters as an array in an HTTP action, like List `abc` and List `xyz`, and then use a model class? public class ItemAndChecque { public List<SaleItem> saleitem { get; set; } public List<itemChecqe> item ...

Is there a way to display tiff files in Google Chrome?

I've been struggling with this problem for over 48 hours now, tirelessly searching for a solution. The issue lies within an application built using the ext.net framework on the front end. Specifically, I'm encountering difficulties when it comes ...