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

Can you please specify the type of values being entered as input?

Query: How do I identify the data type of the value entered in an input field? Whenever I use typeof, it always returns string unless the string is empty. I searched various forums extensively but couldn't find a solution. Can someone assist me with t ...

Is there a way to create a Vue component that can process dynamic formulas similar to those used in

I am looking to create a component that has the ability to accept different formulas for computing the last column. The component should use these formulas in Vuex getters to store the total state values passed to it. Here are the specifications for the c ...

Enhance a collection by incorporating methods to the result of an angular resource query

After executing a query, I am left with an array from the resource: .factory('Books', function($resource){ var Books = $resource('/authors/:authorId/books'); return Books; }) I was wondering if there is a way to incorporate pr ...

Guide to quickly redirecting all 404 links to the homepage on a simple HTML website

Is there a way to automatically redirect clients to the homepage if they click on a broken link in a basic HTML website, instead of displaying a custom 404 page? UPDATE: My website consists of only 5 plain HTML pages hosted on GoDaddy. There is no server- ...

What could be causing the misalignment of the Datepicker calendar in Material UI?

I have integrated a datepicker using the library "@mui/x-date-pickers/DatePicker". import { DatePicker } from "@mui/x-date-pickers/DatePicker"; import { AdapterMoment } from "@mui/x-date-pickers/AdapterMoment"; import { Locali ...

Customizing date colors in JavaScript: A step-by-step guide

var active_dates1 = ["2017-04-02 00:00:00","2014-04-03 00:00:00","2014-04-01 00:00:00"]; $('.datePick', this.$el).datepicker( beforeShowDay: function (date) { for(let date1 of active_dates1){ if (date.getTime( ...

Using a static string in Javascript yields no issues, whereas working with variables can sometimes cause problems

I've been struggling with a problem this morning and it's time to ask for help! I have a JavaScript function that takes the value entered by a user into an autocomplete box, uses AJAX to send that value to a PHP script which then queries the data ...

Steps to turn off the automatic completion feature for orders in WooCommerce on your WordPress website

Looking for assistance with changing the order status from completed to processing. When an order is placed, it automatically goes to completed status which is not the desired outcome. The status should change based on the virtual product purchased. I wou ...

Asynchronous requests in Node.js within an Array.forEach loop not finishing execution prior to writing a JSON file

I have developed a web scraping Node.js application that extracts job description text from multiple URLs. Currently, I am working with an array of job objects called jobObj. The code iterates through each URL, sends a request for HTML content, uses the Ch ...

What is the best way to create a deep clone of an XMLDocument Object using Javascript?

I am currently working on a project that involves parsing an XML file into an XMLDocument object using the browser's implementation of an XML parser, like this: new DOMParser().parseFromString(text,"text/xml"); However, I have encountered a situatio ...

What is the best way to trigger actions from child components within React Redux?

My server contains the following code snippet: <ReactRedux.Provider store={store}><Layout defaultStore={JSON.stringify(store.getState())}/></ReactRedux.Provider> The <Layout> component includes more nested components. Further dow ...

Modify div content based on user selection

I have a question about updating the content of a div based on certain conditions in my code. Here is what I'm trying to achieve: <div class="form-control" ns-show="runningImport" disabled="disabled"> {{input[row.header_safe]}}{{select[row. ...

Exploring the compatibility of Next.js with jest for utilizing third-party ESM npm packages

Caught between the proverbial rock and a hard place. My app was built using: t3-stack: v6.2.1 - T3 stack Next.js: v12.3.1 jest: v29.3.1 Followed Next.js documentation for setting up jest with Rust Compiler at https://nextjs.org/docs/testing#setting-up-j ...

What is the best way for Flask to host the React public files?

When working with React, I created a folder called ./public/assets, and placed an image inside it. Running npm start worked perfectly fine for me. However, after running npm run build in React, I ended up with a ./build folder. To solve this issue, I moved ...

In Angular, what is the best way to update the quantity of an item in a Firestore database?

Whenever I attempt to modify the quantity of an item in the cart, the quantity does not update in the firestore database. Instead, the console shows an error message: TypeError: Cannot read properties of undefined (reading 'indexOf'). It seems li ...

Using Material UI with React hooks

I'm encountering an error while trying to incorporate code from Material UI. The error message is: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. Mismatc ...

Avoiding the opening of a select menu

Is there a way to prevent the dropdown menu from appearing when a select element is clicked in a form? I have attempted two methods but they did not work: $('select').click (function (e) { console.log (e); return false; }); and $(&apo ...

Exploring JavaScript and Node.js: Deciphering the choice of prototype.__proto__ = prototype over using the

Currently exploring the Express framework for node.js and noticed that all the inheritance is achieved through: Collection.prototype.__proto__ = Array.prototype; Wouldn't this be the same as: Collection.prototype = new Array; Additionally: var ap ...

Linking asynchronous AJAX requests using Angularjs

Currently in my AngularJS project, I have created a service with multiple functions that return promises. The AJAX Service I've Created: angular.module('yoApp') .factory('serviceAjax', function serviceAjax($http) { return ...

Perform an ajax POST call to a server using ajax/jQuery techniques

I am attempting to utilize ajax to send a post request to a different domain and receive a json response. The server is located within my company premises and the logs show that it is indeed sending back a json response. Below are two samples of my attemp ...