0
votes

I will try to explain my problem. I have an array of a particular object and, from this array, I want to create a new one with the value of a particular field of each object.

In order to achieve this, I tried to use array.forEach() method but I get a variable undefined error inside the forEach() function. This is my code:

var values: number[];
measures.forEach((measure)=>{
    values.push(measure.value);
});

I've tried to declare the array values as public (and access this.values) and also to declare it in the function where I make the forEach and neither way worked.

Here is the error I get in the browser (angular CLI reports no problem):

ERROR TypeError: "values is undefined"
1
You must initialize the array: let values: number[] = [];. - ConnorsFan
You need to initialize the values array, not just define. Try values: number[] = []; instead. - Krishna Teja Veeramachaneni

1 Answers

2
votes

Try to initialize your array rather than just declare it as

values: number[] = [];

You do not need the var keyword in angular if you are declaring a variable directly inside a component class. If you need to do it inside a function, use let keyword. more information HERE