0

I am trying to loop through the array of items and pushing to another array, I have got items list an index "0" but still able to get the error as mentioned in question. Please find the below code

  createReportFormulaInfo(): Array<ReportFormulaEntity> {
    debugger;
    for (let sta in this.selectedSources) {
      debugger;
      let ido = this.selectedSource[sta].id;
      this.selectedFormulaList.push({
        Market_OV: this.selectedSources[sta].Market,
        Set_Name: this.selectedSources[sta].Value,
        Data_ID: Number(this.selectedSources[sta].Market),
        Set_number: 0,
        Formula_Set1: "",
        Formula_Set2: "",
        Formula_type: "",
        Date_From: "",
        Date_To: "",
        UpdateFlag: "A",
        Is_Current: 0
      });
    }
   }

I am not sure how can i overcome this issue and I am using angular 4. Could anyone please help on this query. many thanks in advance.

Glory Raj
  • 17,397
  • 27
  • 100
  • 203
  • 1
    Probably your `this.selectedSources` is **undefined**. Without the full code I can't say more than this – vrintle Oct 11 '18 at 17:22
  • @rv7 if `this.selectedSources` is undefined, how do you end up inside the loop? – Mark Oct 11 '18 at 17:23
  • 1
    You probable already know that `for…in` is a [bad way to iterate an array](https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea), but it's hard to know exactly what's going on without seeing the value of `this.selectedSources`. Can you make an example that shows the problem in a way we can reproduce? – Mark Oct 11 '18 at 17:25
  • if you are looking to transform an `Array` to an `Array`, I suggest using `Array.map()`. The code you posted is unclear, as you defined a return type for `createReportFormulaInfo()`, but don't return anything. – joshvito Oct 11 '18 at 17:56

1 Answers1

1

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#Array_iteration_and_for...in

Note: for...in should not be used to iterate over an Array where the index order is important.

You will have iterate based on a local variable

 createReportFormulaInfo(): Array<ReportFormulaEntity> {
    debugger;
    for (i=0;i<this.selectedSources.length;i++) {
      debugger;
      let ido = this.selectedSource[i].id;
      this.selectedFormulaList.push({
        Market_OV: this.selectedSources[i].Market,
        Set_Name: this.selectedSources[i].Value,
        Data_ID: Number(this.selectedSources[i].Market),
        Set_number: 0,
        Formula_Set1: "",
        Formula_Set2: "",
        Formula_type: "",
        Date_From: "",
        Date_To: "",
        UpdateFlag: "A",
        Is_Current: 0
      });
    }
   }

Another ways is to use array's foreach method

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Pavan Andhukuri
  • 1,547
  • 3
  • 23
  • 49