3

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 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

});

1 Comment

My code works above -- my questions is on the lines of code with indexes. this.tests[0].testresults.push(this.qryresults); this.tests[1].testresults.push(this.qryresults);
0

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);

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.