gene
gene

Reputation: 146

javascript array member of object

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

Upvotes: 0

Views: 903

Answers (2)

James Daly
James Daly

Reputation: 1406

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])
}

Upvotes: 0

TGH
TGH

Reputation: 39268

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

topObj.x.push(xobj);

Upvotes: 2

Related Questions