PaReeOhNos
PaReeOhNos

Reputation: 4398

Javascript structure

I'm having an issue getting the structure of my JS code right. I'm basically trying to create a complex object which contains other objects.

What I'm after is basically something like :

object {
    f1: (),
    f2: (),
    objA: {
        objA: {
            v1: ""
        }
    },
    objB: {
        objA: {
            v1: "",
            v2: "",
            f1: ()
        }
    }
}

Or something similar to this. I had something kinda of working, but in the object, I want to be able to reference other parts of the object.

So for instance, with the example above, I'd like to set the variable object.objA.objB.v1 to be equal to the value from object.objA.objA.v1

When I tried this, I just got an error saying it couldn't access objA of undefined.

How can I get around this or restructure it to make it work?

Upvotes: -1

Views: 176

Answers (3)

Mateusz Rogulski
Mateusz Rogulski

Reputation: 7445

Your example throws an error because it is invalid. Simply object.objA.objB.v1 doesn't exist. But if you want to use the properties from objects which exist you can do it simply by:

var yourObj =  {
objA: {
    objA: {
        v1: "a"
    }
},
objB: {
    objA: {
        v1: "b",
        v2: "c",
    }
}
}

yourObj.objB.objA.v1 = yourObj.objA.objA.v1;
alert(yourObj.objB.objA.v1); 

jsFiddle

Upvotes: 1

Vivin Paliath
Vivin Paliath

Reputation: 95508

Object literals are not self-referential. You cannot reference something that hasn't been defined yet. This is why you're getting an error.

What you can do is defer definition of self-referential properties after the structure has been initially defined.

So initially define your object:

var obj = {
    a: {
        prop1: 1
    },
    b: 2,
    innerObj: {}
};

Then:

obj.innerObj.a = obj.a;

Keep in mind that this won't work for primitive types like numbers. This will work for objects that have references, like functions and other objects/arrays.

Upvotes: 0

earl3s
earl3s

Reputation: 2373

Unfortunately in Javascript when defining object literals you cannot reference other parts of the object to itself. So:

object.objA.objB.v1: object.objA.objA.v1 is not legal. It has no reference to object yet because it's not finished being defined.

What you could do is define the object, and afterward set specific values on it. They would not update automatically though unless they were also objects and therefore being passed by reference.

A possible solution is that object.objA.objB.v1 could be a function that returns the value of object.objA.ovjaA.v1.

Upvotes: 0

Related Questions