changing an object into an array using Angular 2's TypeScript

I am currently facing an issue where I have an object within another object, and my goal is to convert the inner object into a string separated by commas. However, when I attempt to do so, it results in an infinite loop.

After making an observable http request, I receive the data in the following manner:

this._categoryService.getChecklistCategories()
  .subscribe(
    res => {
      this.categories = res;
      let newitem:string[];
      for(var i=0; i<res.length; i++){
        this.categories.map((category, i) => category.no = i+1);
        var obj = res[i].assigned; //an obect.
        console.log(obj[0]); //get the first index
     }
    })

The log of 'obj[0]' above displays

https://i.sstatic.net/TSYIx.png

My objective is to generate a string of 'truck_subtype' and append it to this.categories

I attempted the following approach:

     res => {
       this.categories = res;
       let newitem:string[];
       for(var i=0; i<res.length; i++){
           this.categories.map((category, i) => category.no = i+1);//this adds no i,2,3...
           var obj = res[i].assigned; //array item
            let stringArray: Array<any> = [];  
           for(var i=0; i<obj.length; i++){
                  stringArray.push(obj[i].truck_subtype);
                    
            }
             this.categories.map((category, i) => category.assigned= stringArray)                

      }
    }

However, the code above leads to an infinite loop and fails to add the string array to this.categories

I'm unable to figure out where I may have gone wrong. Any insights would be appreciated.

Answer №1

It seems like the variable `i` is being redefined multiple times (in for loops and in map functions), which might be causing your index to never reach the res.length since it keeps getting reassigned.

You could try renaming the `i` variables inside the map functions to something like `i2`, and then test if that resolves the issue with the loops.

 res => {
   this.categories = res;
   let newitem:string[];
   for(var i=0; i<res.length; i++){
       this.categories.map((category, i2) => category.no = i+1);//this adds no i,2,3...
       var obj = res[i].assigned; //array item
        let stringArray: Array<any> = [];  
       for(var i3 =0; i<obj.length; i++){
              stringArray.push(obj[i3].truck_subtype);

        }
         this.categories.map((category, i4) => category.assigned= stringArray)                

  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Module not found when attempting to import a newly created TypeScript module

A fresh Typescript project called puppeteer-jquery has just been released on the NPM registry. The code is functioning perfectly well. However, when attempting to integrate it into another project: npm install puppeteer-jquery and trying to import it lik ...

Is there a way to prompt the browser's default handler to execute prior to the event propagation?

When working with a textbox (<input type="text">) in the browser, it's important to note that keystrokes are not processed until after all JS event handlers have completed execution. In my application, I encountered a scenario where a ...

Tips for constructing node.js projects using local versions of the dependencies?

Recently, I've been tackling a rather intricate node.js project (find it at https://github.com/edrlab/thorium-reader/) while trying to incorporate local versions of certain dependencies. Surprisingly, I can successfully build and execute the project ...

Importing 100 .ts files in a dynamic manner

Forgive me for my lack of experience in TypeScript, but I have a query regarding loading multiple .ts files. Imagine I have a directory containing 100 .ts files. Is it appropriate to load all these files using the fs module, as shown below? readdirSync(__ ...

How to Utilize Knockout's BindingHandler to Integrate JQuery.Datatables Select Feature?

I've developed a custom KO bindingHandler (view it here) to assist in updating the DataTable. The documentation for JQuery.DataTable.Select regarding how to access data requires a handle. You can see the details here. var table = $('#myTable&a ...

Summing over array slices while leveraging vectorization

Let's say I have a three-dimensional array: set.seed(1) foo <- array(rnorm(250),dim=c(5,10,5)) If I want to create a matrix that sums each row and layer across columns 4, 5, and 6, I can use the following code: apply(foo[,4:6,],c(1,3),sum) Howe ...

Disabling click events on a span tag in Angular 6: A step-by-step guide

Is there a way to disable the click event for deleting hours with the 'X' symbol based on a condition? Thank you in advance. <table navigatable class="<some_class>"> <tbody> <tr *ngFor="let item of ...

Create identical PDF files from HTML content on both the client and server side

Is it possible to create an identical PDF from HTML using the same library or a different method while maintaining the formatting in Angular 6 and .NET Core? I am looking to show a preview first and upon user confirmation, make an API call. Any guidance ...

Is it possible to create a 3-dimensional array from a 2-dimensional array using pandas?

I am looking to transform a 2D array into a 3D array. Starting with the following: U A B C 0 1.438161 -0.210454 -1.983704 1 -0.283780 -0.371773 0.017580 2 0.552564 -0.610548 0.257276 3 1.931332 0.649179 -1.349062 4 1.65 ...

Discover the steps to implement user authentication with a combination of username, password, and token in an Angular 4

After developing a form using Angular 4, I encountered the need to send the form data via the post method with Angular 4. Testing with Postman showed that the data is being received correctly. To accomplish this, I must use Basic Auth with a username and p ...

The issue with Angular 4 imports not refreshing in a .less file persists

Currently, I am in the process of developing a small Angular project that utilizes less for styling purposes. My intention is to separate the styling into distinct folders apart from the components and instead have a main import file - main.less. This fil ...

Utilizing the <HTMLSelectElement> in a Typescript project

What exactly does the <HTMLSelectElement> do in relation to a TypeScript task? let element = <HTMLSelectElement> document.querySelector('#id_name'); The HTMLSelectElement interface, similar to the one mentioned in TypeScript, is exp ...

Navigating between routes in Angular can lead to multiple subscriptions being created

One issue I've encountered is receiving multiple subscriptions as I switch between routes in my Angular application. Within my parent component, I have defined the following routes: <li routerLink="route1" [routerLinkActive]="[&apos ...

Switching an Enum from one type to another in JavaScript

UPDATE After reading a comment, I realized that Enum is not native to JavaScript but is actually part of TypeScript. I decided to keep the original title unchanged to help others who may also make the same mistake as me. I am faced with a scenario where ...

Working with 2D arrays in C++ and C# can be challenging, especially when

I am having trouble deleting a C++ pointer in my C# application. Whenever I attempt to delete the pointer, the application crashes. Here is a snippet of my C# code: IntPtr jointAreaPointer = IntPtr.Zero; This pointer holds a reference to a C++ pointer tha ...

Exploring nested list iteration in Python

I have a total of 43 items, each consisting of 75 data points. These 75 points represent different times of the day, and I am looking to calculate the standard deviation of each specific time across all 43 items. I attempted to use a nested for loop, but i ...

Looking to accentuate specific columns in highcharts upon clicking?

https://i.sstatic.net/R3Y19.png Essentially, the image above serves as a reference idea on the webpage, showcasing four individual highchart charts. Each chart is initialized using the following code: this.chart2 = new Chart( { chart: { ...

Retrieve the value of a local variable in the ngOnInit function from a different function

Recently, I've started working with Angular and TypeScript. I am facing an issue where I need to access a local variable that is declared in the ngOnInit function from outside it, but I'm not quite sure how to achieve this correctly. This variabl ...

Enhance Component Reusability in React by Utilizing Typescript

As I embark on developing a React application, my primary goal is to keep my code DRY. This project marks my first experience with Typescript, and I am grappling with the challenge of ensuring reusability in my components where JSX remains consistent acros ...

Utilizing Custom Validators in Angular to Enhance Accessibility

I'm struggling to access my service to perform validator checks, but all I'm getting is a console filled with errors. I believe it's just a syntax issue that's tripping me up. Validator: import { DataService } from './services/da ...