Is there a way to alter the data type of a JavaScript object?

Currently, I'm developing a browser-based text adventure game that takes inspiration from classics like Hitchhiker's Guide to the Galaxy and the Zork series. In order to allow players to save their progress, I store important objects such as locations and player data in localStorage.

To handle circular references within these objects during saving process, I've implemented the use of CircularJSON.

The challenge arises when these saved objects are parsed back, as they default to being of the Object type. This poses an issue for functions associated with specific types like Area:

var Area = function (tempdescription, tempinitialDesc, tempobjArr) {
    // Area object properties and methods
};
Area.prototype.getIndex = function (tempstr) {
    // Method to get index of a specified string in the objArr array
};

and Player:

var Player = function (defaultLocation) {
    // Player object properties and methods
};

Player.prototype.getIndex = function (tempstr) {
    // Method to get index of a specified string in the inv array
};

In my game, it is crucial for objects like Area and Player, which I have defined myself, to maintain their correct types for the rest of the code to function properly.

Given that there will be numerous instances of these objects by the end of development, I am looking for a simple method to change their types efficiently while retaining their structure.

Is there any way to modify the type of a JavaScript object without extensive manual adjustments?

Answer №1

Approach 1 (utilizing ES2015):

const freshObject = Object.setPrototypeOf(existingObject, Player.prototype)

However, this method can be sluggish as per the official documentation:

Caution: Modifying the [[Prototype]] of an object is inherently slow due to how contemporary JavaScript engines optimize property accesses, across all browsers and JavaScript engines.

This serves as a substitute for...

Approach 2 (outdated):

existingObject.__proto__ = Player.prototype

Approach 3:

const freshObject = new Individual(/* Utilize the characteristics of existingObject */)

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

Disable Jquery toolstrip while the menu is open

Currently, I am utilizing the jQuery toolstrip plugin in my project. I have a requirement to disable it whenever the sidebar menu is opened. Below are the HTML codes for my menu with li tags: <div class="sidebar-wrapper" id="sidebar-wrapper"> <ul ...

Tips for retrieving values from numerous checkboxes sharing the same class using jQuery

Currently, I am struggling with getting the values of all checkboxes that are checked using jquery. My goal is to store these values in an array, but I am encountering difficulties. Can anyone provide me with guidance on how to achieve this? Below is what ...

Revolutionize Your App with React Native's Interactive Bottom Sheet Option

Hello there! I am trying to create a FlatList with multiple items, each of which should trigger a bottom-sheet when clicked. I want to make this dynamic but I'm encountering an error. TypeError: undefined is not an object (evaluating `_this[_reactNat ...

Animations are failing to run within a Bootstrap card when using Vue rendering

I have utilized Bootstrap cards to display pricing information in my project. I implemented a collapse feature for half of the card when the screen size is equal to mobile width. While using vanilla Bootstrap, the animation worked seamlessly with the col ...

Filtering substrings in an Angular data resource

DEFAULT_RECORDS = [{ id: 1, name: 'John Evans', number: '01928 356115' },{ id: 16, name: 'Murbinator', number: '053180 080000' }]; - retrieveEntries: function (name) { var foundRecords = {}; ...

Get rid of the spaces in web scraping <tr> tags using Node.js

I've encountered a problem that goes beyond my current knowledge. I'm attempting to web-scrape a specific webpage, targeting the <tr> element in nodejs. Although I can successfully retrieve the content, it seems that the format is not as cl ...

Using Node.js and TypeScript to define custom data types has become a common practice among developers

I offer a variety of services, all yielding the same outcome: type result = { success: boolean data?: any } const serviceA = async (): Promise<result> => { ... } const serviceB = async (): Promise<result> => { ... } However, th ...

Why isn't my div displaying in JavaScript?

Currently working on a project for the Odin Project front-end web development. My task involves creating a grid using javascript/jQuery. I attempted to use the createElement method but have encountered an issue in making the div visible within the html. Am ...

What is the best way to showcase the content from multiple uploaded files?

Below is an example demonstrating how to display the contents of a single uploaded file. .js $scope.uploadFilename = function (files) { if (!files[0]) { return; } var reader = new FileReader(); reader ...

Creating mesmerizing noise animation using THREE.FilmPass() in Three.js

Chapter Eleven of my Learning Three.js book showcases a fascinating noise animation created by the author using var effectFilm = new THREE.FilmPass(0.8, 0.325, 256, false); In the code example from the book, it is interesting to note that removing the orb ...

Why is my React component not updating after changing the state using Set State?

Uncovering the elusive problem seems impossible. Despite state changes, the component remains unrerendered. Here's the code: export const InterestsPupup: React.FC = ({interests, title, buttonText}) => { const [activeItems, setActiveItems] = useSt ...

Choose a looping function in React JS that iterates over an array of objects

I have an array of objects let arr = [0: {received: "Return Received", approved: "Approved", rejected: "Rejected"} 1: {authorized: "Authorized", received: "Return Received"}} I am looking to populate a < ...

How can you reset the chosen option in a Vue.js dropdown menu?

Within my dropdown menu, I have included a button that is intended to clear the selected city. Despite adding an event, the selected option is not being cleared. Can anyone provide insights on what I might be missing? Thank you in advance. Below is the bu ...

Access information via ajax from a php script

I am currently working on an AJAX code that sends data to PHP and then receives data from PHP... function updateDatabase(syncData){ $.ajax({ type : 'POST', async: false, url : 'php/syncData.php', ...

struggling to send variables to jade templates with coffeescript and express.js

As a newcomer to node and express, I am currently building the front end of an application that utilizes jade as its templating engine. Despite extensive searching online and within this community, I have not been able to find a solution to a particular is ...

Angular's UI Modal: utilizing inline template and controller functionality

I am looking to create a simple confirmation box using UI-modal, which I have used successfully for more complex modals in the past that load their template and controller from external files. However, this time I want something even simpler - just a basi ...

Ways to employ data binding for extracting a user-input value and performing multiplication operations with the enclosed {{ ...}} tags

My API response includes the price of a product, which is represented as {{price}} I have a system where I can add or reduce the number of products: <div class="number-input"> <h2>Price: {{price }}</h2> <button oncli ...

Remove user from firebase with Admin SDK

I need help understanding how to remove a user from my admin panel using the Firebase Admin SDK. When attempting to delete a user, I encountered this error: Uncaught (in promise) ReferenceError: uid is not defined at eval (ManageCustomer. ...

Click once to change the element, but it will remain changed and will not revert back no matter how many times you

After the first click displaying "X" and then changing to "O" in my tic-tac-toe JavaScript game, subsequent clicks only show "O", failing to switch back to "X". I am currently working on creating a tic-tac-toe game using JavaScript. Upon the first click, ...

Incorporating onPause and onResume functionalities into a YouTube video featured on a page built with Ionic 2

I'm encountering a minor problem with a simple demo Android app built in Ionic 2. Whenever a Youtube video is playing on the Homepage, if the power button is pressed or the phone goes into sleep/lock mode, the Youtube video continues to play. This is ...