Stephen
Stephen

Reputation: 1991

Two Dimensional Object / Associate Array into Three Dimensional Object Javascript

Is there anyway to go form this

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

To this

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

Dynamically in a function? For example, this doesn't work…

turn = 1;

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

Upvotes: 0

Views: 1332

Answers (1)

T. Stone
T. Stone

Reputation: 19495

The history part of it could be an array of objects. So...

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

Or if you needed to reference every 'step' in the history by a key, it could be a object with array values containing objects...

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

In the latter case, the "start" code would be something like...

turn = 1

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

Having said all that, I feel inclined to mention that using an object to contain all of this state data would be a good decision. Consider for example...

// Define our manager
var stateDatManager = function() { };
(function(instance) {

    instance.init = function() {
        // Setup 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;
    };

}(stateDatManager.prototype));

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

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

// etc.

Upvotes: 1

Related Questions