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

The functionality of nested dynamic routing in the API is experiencing issues

Looking to extract product details from a specific category of products? My folder structure appears as follows: https://i.stack.imgur.com/1UCy3.png In "productId/index.jsx" => This snippet is utilized to retrieve individual product details: ...

"Encountered a TypeError: Cannot read property 'params

I've encountered an issue with passing the id to my product page. Despite trying various solutions and searching for answers, I still can't get it to work. Below is my index.js code: import React from "react"; import {render} from &quo ...

Generating various API calls and delivering them to a template (Express + Node.js + Facebook open graph)

I am currently developing a unique Express Node.js application that utilizes the extraordinary capabilities of this remarkable Facebook SDK. Allow me to present my existing route for the root: app.get('/', Facebook.loginRequired(), function (req ...

What could be causing the entire app to malfunction when the Redux Provider tag is used

I am facing an issue while trying to integrate a React Toolkit app into my project. The error message I encountered is as follows: Error: Invalid hook call. Hooks can only be called inside the body of a function component. This error may occur due to one ...

Finding the identification of the first element within a nested div using JQuery

Here is the HTML snippet that I am working with: <div id="parent"> <div id="computer"> <div id="items"> <div id="1">hp</div> <div id="2">compaq</div> <div id="3"& ...

Is there a way to customize the color of the HR element in a Material-UI Select Field?

https://i.stack.imgur.com/DYeX7.png https://i.stack.imgur.com/CN0T6.png Hi there, I am currently working on a website and using a Select Field component from Material-UI. I am faced with the challenge of customizing the style to change the default light ...

React does not display the items enclosed within the map function

I am facing an issue with rendering elements from a map function. Despite trying to modify the return statement, I have not been able to resolve the issue. class API extends Component { myTop10Artists() { Api.getMyTopArtists(function (err, data) { ...

Retrieving data from intricate JSON structures

Currently, I am engaged in web scraping to extract the "id" of all locations from a complex json content. Click here for the JSON link I attempted using the dict.items method, but it only extracted 2 values at the start of the dictionary followed by a li ...

Are Primereact and MUI JOY Styling at Odds?

here is the image of datatables and button I am currently using Primereact and MUI Joy in the same project, but I am facing an issue where the Primereact styling does not load properly. I'm not sure if it's due to a conflict with MUI Joy or some ...

Retrieving checkbox value upon form submission

Imagine having a form containing several checkboxes. Upon submitting the form, you aim to display all values of the selected checkboxes. <form> <input type="checkbox" id="product1" name="product1" value="12"> <input type="checkbox" id="prod ...

Utilizing AJAX to dynamically update a div on a separate webpage

In my application, I have a page called news.jsp that displays a list of news titles. Users can click on a title to read the full body of the news, which is loaded using AJAX within a span tag on the same page. Additionally, I display the top 5 news storie ...

Instead of throwing an error, JSON Schema inserts null values for failed validation on nested objects

My current dilemma involves using fastify in conjunction with fluent-json-schema to validate server requests and responses, specifically struggling with nested validations utilizing oneOf. Here is an example of the schema I am working with: const textTypeS ...

Upon the second click, the addEventListener function is triggered

When using the window.addEventListener, I am encountering an issue where it only triggers on the second click. This is happening after I initially click on the li element to view the task information, and then click on the delete button which fires the eve ...

The error occurs when Facebook and Twitter iframes are attempting to access and set 'document.domain'

When attempting to add Tweet and Facebook Like buttons to the project I'm working on, everything appears to be functioning properly. However, upon clicking the buttons, a JavaScript error occurs: Unsafe JavaScript attempt to access frame with URL htt ...

Why is my bindingResult returning null even after the Spring Validator detects duplicates in my code?

Below is the registration controller method for Sensor, kept simple: @PostMapping("/registration") public ResponseEntity<HttpStatus> create(@RequestBody @Valid SensorDTO sensorDTO, Bindin ...

What steps can I take to troubleshoot the "Element type is invalid" error in my React application?

I am currently restructuring my initial code for better organization. Click here to view the code on CodeSandbox. However, I'm facing issues with integrating child components into my code. For example, in this instance, I showcase how I import a chi ...

Navigating between interfaces without the need to constantly refresh or reload

Currently, I am in the process of developing a website using ASP.NET MVC that allows users to navigate between pages without refreshing each time. My approach involves treating views as 'areas' or mini master pages, utilizing partial views inste ...

Loading local JSON data using Select2 with multiple keys can greatly enhance the functionality

Comparing the select2 examples, it is evident that the "loading remote data" example contains more information in the response json compared to the "loading array data" example. I am interested in knowing if it is feasible to load a local json file with a ...

Look into the data with vue.js, but there's not much

1. As a newcomer to vue.js, I encountered some surprising issues while experimenting with examples. The first one arose when I assigned an id to the body tag and included the following JavaScript code: <html> <head> <meta charset="utf-8 ...

Unable to modify variable to play audio

As I work on constructing my website, I am incorporating various sounds to enhance user experience when interacting with buttons and other elements. However, managing multiple audio files has proven challenging, as overlapping sounds often result in no aud ...