Turning a Two Dimensional Object or Associate Array into a Three Dimensional Object using Javascript

Is there a method to transform the following:

var stateDat = {
ME: ['Maine',1328361],
etc.
};

Into this structure dynamically within a function?

var stateDatHistory = {
1:[
  ME: ['Maine',1328361],
  etc.
  ],
2:[
  ME: ['Maine',1328361],
  etc.
  ],
etc
};

An attempted solution that doesn't work is shown below:

turn = 1;

function start(){
stateDatHistory[turn].push(stateDat);
stateDat['ME'][1]= stateDat['ME'][1] - 500; //changing population
turn++;
}

Answer №1

Perhaps the historical aspect could be structured as an array of objects. For instance...

var historicalData = [
   { ME: ['Maine', 1328361] }
];

Alternatively, if you want to reference each historical 'step' using a key, you could organize it as an object with arrays containing objects...

var historicalData = {
    1: [
        { ME: ['Maine', 12334] }
    ]
}

In the latter scenario, the starting code might look something like this...

turn = 1

function start() {
    if (typeof historicalData[turn] === 'undefined') {
        historicalData[turn] = [];
    }
    historicalData[turn].push(stateDat);
    stateDat['ME'][1]= stateDat['ME'][1] - 500; //adjust population
    turn++;
}

With that being said, utilizing an object to store all the state data seems like a wise choice. Take for instance...

// Create our manager
var stateDataManager = function() { };
(function(instance) {

    instance.init = function() {
        // Establish internal state
        this.history = {};
        this.turn = 0;
        this.initialized = true;
    };

    instance.start = function(turn, data) {
        if (!this.initialized) { this.init(); }
        this.turn = turn;
        this.addToHistory(data);
    };

    instance.addToHistory(data) {
        if (typeof this.history[this.turn] === 'undefined') {
            this.history[this.turn] = [];
        }
        this.history[this.turn].push(data);
    };

    instance.advanceTurn() {
        this.turn += 1;
    };

}(stateDataManager.prototype));

// Utilize it
var manager = new stateDataManager();
manager.start(1, [
    { ME: ['Maine', 1328361] }
]);

// Progress to the next turn...
manager.advanceTurn();

// etc.

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

What is more costly in terms of performance: toggling the visibility of a DOM node or adding/removing a DOM node?

When it comes to calling, which is the more costly operation? Displaying and hiding a DOM node Creating and deleting DOM nodes Let's assume we only have one or a few (less than 5) nodes that require manipulation, and the application is running on a ...

Maintaining the user interface state while utilizing $resources in AngularJS

For my app, users have the ability to create and delete items. I've implemented $resources for this functionality, which is working really well. However, I'd like to implement a loading screen that appears whenever a request is being processed. ...

Interactive tooltip with hyperlinks powered by jQuery

Is it possible to create a pop-up window with links that behave like a normal tooltip but can be clicked on by the mouse? How can this functionality be achieved without losing focus when hovering over the links causing the window to close? jQuery(docume ...

The AngularJS element fails to display on the screen

I am currently learning AngularJS and I am struggling to understand how components are linked to the view in the tutorial. I have created a component that is quite similar: angular.module('phonecatApp').component('nameList', { temp ...

What are the steps for implementing Babel in a CLI program?

Currently, I am working on developing a CLI program in Node using Babel. While researching, I came across a question on Stack Overflow where user loganfsmyth recommended: Ideally you'd precompile before distributing your package. Following this ad ...

Submitting a form through Ajax is resulting in multiple submissions

Whenever I use Ajax to submit this form, it ends up posting multiple times without any obvious reason. Sometimes, it posts the form up to 10 times even though the submit button is clicked only once. I'm puzzled as to why this behavior is happening. An ...

The jQuery AJAX call is successful in Firefox, but unfortunately, it is not working in Internet Explorer

I've encountered a perplexing issue with an AJAX call. It's functioning perfectly fine in Firefox, but for some reason, it's not working in IE. Curiously, when I include an alert() specifically for IE, I can see the returned content, but the ...

Retrieve the ActiveTabIndex value from an Ajax TabContainer using Javascript

Is there a way to retrieve the ActiveTabIndex from TabContainer when a tab is selected by the user? I've attempted the following approach without success. <script type="text/javascript"> function GetActiveTabIndex() { var tc = docum ...

I'm experiencing an issue with my API where it is returning invalid JSON data when I make a POST request using

I have a scenario where I am making a post request to my Next.js API for updating an address. The code snippet below shows the function that handles fetching: async function handleSubmit() { const data = { deliveryAddress, landmark, pincode, district, bl ...

Ways to remove an item from firebase database

Currently, I am exploring ways to delete data stored in the Firebase database specifically under the requests category. Check out this example Below are the functions I have implemented to fetch and manipulate the data: export default { async contactArtis ...

Error message "e.nodename undefined when set to setTimeout" was encountered

I developed a unique piece of code for input boxes located at the top of different tables. By using a class='filt', the table can be filtered based on the inputs provided. However, most of the inputs consist of more than one letter, so I wanted t ...

Ways to retrieve information from a intricate JSON structure?

Can anyone help me understand why I am unable to access the data in the detail option of the JSON? My goal is to load the firstName, lastName, and age into a list for each object. var data = { "events": [{ "date": "one", "event": "", "info ...

Angular 4: The Authguard (canActivate) is failing to effectively block the URL, causing the app to break and preventing access to all resources. Surprisingly, no errors are being

I have created an authguard, but it seems to not be blocking the route when the user is logged out. The authentication workflow in the app works fine, as I am using traditional sessions on the backend database. I have also verified the state of the auth se ...

Is the UUID key displayed as an object within a Reactjs prop?

Hey there internet pals, I've stumbled upon a mysterious corridor, so dark that I can't see where I'm going.. could really use someone's flashlight to light the way. I have put together a basic, no-frills to-do list program. It consi ...

Tips for creating a Material UI (next) dialog with generous top and bottom margins that extend off the screen

I am encountering a challenge with the layout. What am I looking for? I need a modal dialog that expands vertically, extending beyond the screen, centered both horizontally and vertically, with minimal margin on the top and bottom. Is this feature not d ...

It is impossible for Javascript to access an input element within a gridview

I have developed an asp.net page that allows a site administrator to select a user as the 'systems chair'. The page displays users in a gridview and includes a column of radio buttons to indicate who the current chair is or to change the assigned ...

The outcomes of my JavaScript code are not aligning with my expectations

I've been experimenting with printing objects from an API using JSON and AJAX, and I noticed that the console.log works perfectly to display the output. However, I'm having a bit of trouble with my generateCreatureDiv function as it doesn't ...

After receiving a data token from the server in one controller, how can I efficiently utilize that token in a different AngularJS controller?

In my adminSearchCtrl controller, I am receiving data from the server in the form of a token and want to pass that token to another controller named "adminViewCtrl". How can I achieve this? adminSearchCtrl.js $scope.getUserDetails = function(selectedUser ...

Efficiently transferring components of a JavaScript project between files

For the first time, I am creating an npm package using ES6 and Babel. However, I am facing difficulties in connecting everything together so that it can be imported correctly by the end user. The structure of my build (output) folder is identical to src: ...

What is the best way to incorporate a state variable into a GraphQL query using Apollo?

My current challenge involves using a state as a variable for my query in order to fetch data from graphQl. However, I'm encountering an issue where the component does not read the state correctly. Any suggestions on how to solve this? class usersSc ...