FlyingCat
FlyingCat

Reputation: 14260

javascript array/object issue

I am trying to push elements onto an array.

EDIT

 task.prototype.goTest=function(){

     for(a = 0; a < test.length; a++) {
        if(this.testnumber != test[a].number) {

            //it will only loop 8 times under conditional statement            
            group = {
                title: test[a].Title,
                ID: test[a].ID,
                contents: []
            };

            this.company.push(group);
            this.testnumber = test.number[a];
        }
        //outside of if conditional statement.. it will loop 15 times
        //i want every test[a].conetents get pushed to group.contents array. 
        //this.company is the final variable I need for this function...    

        group.contents.push(test[a].contents);
    }
    console.log(this.company);
}

However, when I do

console.log(this.company);

I see 8 elmements with only 1 element in each group.contents array. The ideal situation is to have 8 elements with 2 to 3 elements in the group.contents array.

this refers to the object in the function. Any idea how to solve my issue?

Upvotes: -1

Views: 65

Answers (1)

gen_Eric
gen_Eric

Reputation: 227240

You are making a new group object each loop, so the reference to group.contents is only the current one, it does not reference the previously created group objects.

So, each time you call group.contents.push, you are only pushing onto the object created in that loop iteration.

Upvotes: 1

Related Questions