Why would Angular push index 0 array into a sub array and not index 1?

Viewed 277

I have the following Array setup in my oninit:

 this.tests = [{
      status: 0,
      testresults: [{       
        name: 'test',
          id: 1
      }]
    }
    ]
    ;

    this.tests.push([{
      status: 1,
      testresults: [{       
        name: 'test2',
          id: 2
      }]
    }
    ]
    }]);

This array works as expected. My goal is to push a queries results into the testresults array that is inside tests.

  this.tests[0].testresults.push(this.qryresults);
  this.tests[1].testresults.push(this.qryresults);

Index 0 works correctly, Index 1 gives back the following error:

"ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'push' of undefined
TypeError: Cannot read property 'push' of undefined"
3 Answers

You are pushing an array the second time around instead of an extra object, which results an error because the array you've pushed does not have the property testresults. Please refer to the code snippet below for a working revision of the code:

(function() {
  this.qryresults = "some test data"
  this.tests = [{
    status: 0,
    testresults: [{
      name: 'test',
      id: 1
    }]
  }];

  this.tests.push({ // <--- removed [ here
    status: 1,
    testresults: [{
      name: 'test2',
      id: 2
    }]
  });              // <--- removed ] here

  this.tests[0].testresults.push(this.qryresults);
  this.tests[1].testresults.push(this.qryresults);
  console.log(this.tests)
})()

You push array to array. So that, you must add object to array as :

this.tests.push({
  status: 1,
  testresults: [{       
    name: 'test2',
      id: 2
  }]

});

Yeah, you can fix this issue following code;

tests = [{
    status: 0,
    testresults: [{
        name: 'test',
        id: 1
    }]
}];

qryresults = [{
    status: 1,
    testresults: [{
        name: 'test2',
        id: 2
    }]
}]

tests.push(...qryresults);
Related