Transforming varied JavaScript objects into a serial form

In my application, there is a concept of an interface along with multiple objects that implement this interface in various ways. These objects are created using different factory methods, with the potential for more factories to be added as the application continues to evolve.

One example of this implementation:

var Shapes={};
var Shapes.createCircle=function(radius) {
  return {draw:function...}
};
var Shapes.createRectangle=function(width,height) {
  return {draw:function...}
};

The goal is to serialize these shapes into files by having each object store the name of its factory (e.g. "Shapes.createRectangle") and an array of arguments (e.g [10,20]), which will then be saved as a JSON string. This approach ensures that when the objects are deserialized, they can have all their functions and properties restored.

For instance, to save an object, the plan is to store the JSON string:

{"factory":"Shapes.createRectangle","args":[10,20]}

And in future sessions, the object can be reconstructed by dynamically calling the factory method once again.

Are there any potential pitfalls or issues associated with serializing polymorphic objects in this manner?

Answer ā„–1

Possibly. The functionality will be successful only if the objects remain unchanged or if any modifications made can effortlessly revert to their original state using initial arguments.

Managing this may become challenging as the API expands, though not unachievable. It might be beneficial to verify the presence of serialize and deserialize methods in an object and execute them for a structured approach towards customizing serialization procedures when necessary.

Answer ā„–2

One disadvantage of this approach is that by hard-coding the factory function names in your data, you may encounter difficulties if you need to change them later on. Perhaps storing the object type instead would offer more flexibility and resilience against such issues.

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

The result is being presented enclosed in quotation marks within the JSON format

When I attempt to retrieve a JSON string via jQuery using the function below, I encounter an issue where my JSON result is wrapped in double quotes. I came across a post on Stack Overflow, suggesting that I should rely on the JSON serialization of the fram ...

Tips for monitoring a variable within a Service using a Controller to trigger a modal?

http://plnkr.co/edit/bdHiU0?p=preview When I require a variable that is returned by a service, like the data in InitTickersFactory.returnTickers(), I can easily assign it to vm.tickersObject. However, in the plnkr example provided above, I am simply toggl ...

Laravel Model that handles JSON data

Is it possible to write a model in Laravel that does not rely on a database, and includes a function getData that returns JSON? It should resemble the following code: <?php namespace App; use Illuminate\Database\Eloquent\Model; cla ...

An issue occurred while processing the 'serializer build' command in jaguar_serializer

I've been working on utilizing jaguar_serializer to convert my JSON string into a model object. I followed the steps outlined in https://github.com/Jaguar-dart/jaguar_serializer. However, I'm encountering an error message when executing 'ser ...

Utilizing absolute path in Typescript: A comprehensive guide

I am currently working on a project written in Typescript running on NodeJS. Within the project, I have been using relative paths to import modules, but as the project grows, this approach is becoming messy. Therefore, I am looking to convert these relativ ...

Submitting a nested JSON object in an AJAX request

When it comes to passing nested JSON through AJAX, the format of the sample request should be like this: { 'user': { 'email': email, 'password': password } } login(){ var email=document.getElementById(& ...

Is it possible to dynamically append and delete rows of interconnected dropdown menus?

I'm currently working on a form that allows users to add and remove rows with cascading dropdowns for class selection. Everything is functional except for the feature to remove selected classes. I've experimented with different methods like the ...

Convert Java object to JSON format compatible with D3's circle packing visualization

I have a unique data structure in Java that resembles the following public class Folder { private Map<String, Folder> directories = new HashMap<>(); private Map<String, GitFile> files = new HashMap<>(); private String n ...

What is the best Haskell library for handling JSON data?

With approximately twelve JSON packages available on Hackage for Haskell, how can I determine which one is the best fit for my needs? Is there a way to gauge popular opinion on these packages? Is there any data available regarding the usage and popularity ...

Trigger the execution of a Python script through a webpage with just the click of a button

I have a small web interface where I need to control a Python script that is constantly gathering data from a sensor in a while loop. Ideally, I would like the ability to start and stop this script with the click of a button. While stopping the script is s ...

The render props on the child component are not appearing on the screen as expected

Recently diving into React Native, I created a stateless component designed to iterate through props that contain objects with arrays of tags. The goal was to extract and display a single tag from each array item. (Refer to the console log in the screensh ...

Working with numerous query parameters within AngularJS

When interfacing with an external service, Iā€™m receiving query parameters in the following format: url/?error=someError&error_description=someErrorDescription In my app.js file, I have attempted to handle this using the routeProvider as shown below ...

Using Javascript to deactivate a clickable image upon clicking another image

I have two buttons with alert functions assigned to each. I want the function on the first button to only work when that button is clicked, and not work if the second button has been clicked. Below is the code I've tried, but it's not functioning ...

Organizing NodeJS modules in a way that mirrors Maven's groupId concept

I am making the switch to NodeJS after working extensively with Maven. In Maven, we are familiar with the groupId and artifactID, as well as the package name when starting a new project. However, in NodeJS, I only see a module name. The concept of groupI ...

Locating discord.js users who possess multiple roles

Here is my code in its entirety as I have received some confusion on other forums: I am working on creating a Discord bot that can list users with a specific role. The plan is to create an array of roles, compare user inputs to the array, and display user ...

summing 3 numbers to a total of 100 percent

I am currently trying to calculate the percentages of different statuses based on 3 count values. Let's assume I have 3 statuses: 1) Passed 2) Failed 3) Skipped When dealing with only two cases, I was able to use a combination of the Floor and Ceil ...

Issue with the Edit feature causing conflicts with the local storage and generating error messages

There seems to be an issue with my edit function that is causing it to override the local storage when I attempt to save and interfering with my delete function as well. I have searched through similar posts for a solution but have not been able to pinpo ...

Capture a snapshot of a Bootstrap modal using JavaScript

var takeScreenShot = function(){ html2canvas(document.body, { onrendered: function(canvas) { var tempcanvas=document.createElement('canvas'); tempcanvas.width=1350; tempcanvas.height=1350; var context=tempcan ...

How to update the date format in v-text-field

I have run into an issue while working on a Vue.js project that utilizes Vuetify. The problem lies with the default date format of the v-text-field when its type is set to "date." Currently, the format shows as mm/dd/yyyy, but I need it to display in the y ...

Is there a way to track dynamic changes in window dimensions within Vue?

Working on my Vue mobile web app, I encountered an issue with hiding the footer when the soft keyboard appears. I've created a function to determine the window height-to-width ratio... showFooter(){ return h / w > 1.2 || h > 560; } ...and ...