I have 2 objects OldAnswer and NewAnswer. I am trying to convert array of OldAnswer objects to array of NewAnswer objects.
export class AnswerComponent implements OnInit {
answers: OldAnswer[] = [/* some data */];
newanswers: NewAnswer[];
constructor() {
this.answers.forEach(function (answer) {
answer.answers.forEach(function (a){
for (var key in a) {
text = // some logic"";
}
// exception in below line
this.newanswers.push({id: answer.observationId,answer: text});
});
});
}
}
but I am getting " Can't call newanswers on undefined ". Why is this
object undefined
here and not while accessing answers?
you declared array but did not initialize. Fix:
newanswers: NewAnswer[] = [];
Also you need to use arrow function so that your scope will not change
this.answers.forEach(answer => {
answer.answers.forEach( (a) => {
for (var key in a) {
text = // some logic"";
} // exception in below line
this.newanswers.push({id: answer.observationId,answer: text});
}); }); }
you used forEach
with function()
Use arrow functions to define your functions in the forEach
s :
this.answers.forEach((answer) => {
answer.answers.forEach((a) => {
Until arrow functions, every new function defined its own this value (based on how function was called, a new object in the case of a constructor, undefined in strict mode function calls , the base object if the function is called as an "object method", etc.). This proved to be less than ideal with an object-oriented style of programming.
(emphasis mine).
Since Angular / TypeScript will generate strict mode Javascript, the this
will undefined
in the body of a function() {}
, it will not reference the object instance of your class anymore.
Note: there are other "good?-old JavaScript ways" to solve this issue, but the arrow function is really the usual way of doing this now and in most situations like this in TypeScript / Angular / ES6.
push()
on it However, you will also experience the problem that newanswers
is also undefined (at least it isn't in the sample you provided, so as Simonare noticed, you should also get it initialized as an empty array []
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.