0

I am instantiating an object which builds an associative array. After it is instantiated, I want to add properties the object's members, but I'm getting an error when I attempt to do so.

So this is the object, which parses a bunch of xml and builds out the scenes and vehicles arrays:

var supertree = {
    scenes: {},
    vehicles: {},
    init: function() {
        this.parseScenes();
        this.parseVehicles();
    },
...

And when I instantiate the object:

supertree.init();
    supertree.ready = function() {
        assignSpritePos();
    }

I can't add properties to it. This is what I'm trying to do:

function assignSpritePos(){


    var sceneCount = 0;
    var sceneLength = Object.keys(supertree.scenes).length;

    for (i=0; i< sceneLength; i++){
        //console.log(i);
        supertree.scenes[i].index = i;
        sceneCount++;
    }
}

As you can see, all I'm really trying to do is store some permanent reference to its index in the overall object. How do I do this? The error I get is:

TypeError: 'undefined' is not an object (evaluating 'supertree.scenes[i].index = i')
1
  • PS - nothing to do with jQuery or associative-array. Commented Aug 22, 2011 at 23:25

2 Answers 2

4

Assigning properties to objects isn't recursive, i.e. it doesn't create objects automagically for you so you must assign each property individually.

Try this...

supertree.scenes[i] = { 'index': i };
Sign up to request clarification or add additional context in comments.

Comments

0

You can't assign a property to an object that doesn't exist yet. Use this:

supertree.scenes[i] = {};
supertree.scenes[i].index = i;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.