1

I have the following map within a function:

mainFunc(){
// other logics

    data.map(function (item) {
      item.number = Math.round(item.number);
      item.total = item.last - item.first;
      item.quantity= item?.quantity ? quantityRange(item?.quantity): '';
    }); 

// other logics
}


quantityRange(quantity){
if(quantity){
   if(quantity < 100) return "Less Quantity";
   if(quantity < 500) return "Average Quantity";
   else return "Good Quantity"
   }
}

I have the quantityRange() outside the mainFunc() and I am calling it inside the ternary operator inside the map. When I run my code I get the error: quantityRange() not defined. Can we not use functions like this inside the map in typescript?

Any help would be appreciated.

Robert Bradley
  • 548
  • 2
  • 21
Sha
  • 1,826
  • 5
  • 29
  • 53
  • `quantityRange` seems like method declaration. Not a function. You'd need to do `this.quantityRange` but see [How to access the correct `this` inside a callback](https://stackoverflow.com/q/20279484) - since you use a regular function, the `this` value would be wrong. You probably want an arrow function. Although it might be even better if you didn't mis-use `.map()` but use a more appropriate choice - `.forEach()` or maybe even better, a regular loop. – VLAZ Jun 13 '22 at 13:48

2 Answers2

0
mainFunc(){
// other logics
    const self = this; // make sure you are not loosing this
    data.map(function (item) {
      item.number = Math.round(item.number);
      item.total = item.last - item.first;
      item.quantity= item?.quantity ? self.quantityRange(item?.quantity): '';
    }); 

// other logics
}

you should call the method with this keyword, to do so you should bind this. There are different ways to do so, one of them is just to save it in variable.

drent
  • 104
  • 8
0

It is saying that because you haven't defined it. You did not use the keyword function to create either of your functions. You also put a space at data.map(function (item); parentheses should not be separated from this. And there were other syntax errors too. I have fixed most of them, as you can see.
It should be like this:

function mainFunc() {
// other logics

    data.map(function(item) {
        item.number = Math.round(item.number);
        item.total = item.last - item.first;
        item.quantity = item?.quantity ? quantityRange(item?.quantity): ''; // Error is on this line.
    }); 

// other logics
};


function quantityRange(quantity) {
    if (quantity) {
        if (quantity < 100) {
            return "Less Quantity";
        }
        else if (quantity < 500) {
            return "Average Quantity";
        }
        else {
            return "Good Quantity";
        };
    };
};

I was unable to figure out what you were doing with line 6, but that is the only place where the error could be, could you explain to me what your intent is with this line, so that I can help correct its syntax?

Robert Bradley
  • 548
  • 2
  • 21