0

I would like to create in javascript an object that contains an array of other objects. i.e.

var xobj = {
    d: 0,
    e: 0,
    f: 0
};

var topObj = {
    x: [],
    a: 0,
    b: 0,
    c: 0
};

topObj.x[0].d = 1;
topObj.x[0].e = 2;
var xx = topObj.x[0].d + topObj.x[0].e;

console.log( xx );

I would like topObj.x to be an array of xobj.

I am getting:

Uncaught TypeError: Cannot set property 'd' of undefined

0

2 Answers 2

2

You can do that, but you have to populate the array with instances of the object (xobj):

topObj.x.push(xobj);
Sign up to request clarification or add additional context in comments.

3 Comments

Yeap, that works. I guess I have a follow up question: is there a way to declare an array of objects as a property of another object?
Yes, you can initialize "x" to some existing array object instead of an empty array.
After some further testing this does not do exactly what I want. It works on a first element of the array, but all additional elements of the array "x" end up references of the one variable xobj. If I modify one - I modify them all. I would like for array "x" to be an array of different instances of xobj. I.E. if I set topObj.x[1].d = 2; I do not want it to affect [0]. right now it does.
0

if you wanted just the values in the xobj to be appended to the array I would create something like this

for (prop in xobj) {
    topObj.x.push(xobj[prop])
}

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.