Search code examples
angularobjecttypescriptionic2arrayofarrays

Angular2,Ionic2:How to access an array of objects inside another array of objects in typescript?


I'm completely new to the concept of using arrays in angular2. I've my JSON data coming from the backend which I'm storing in an array called "arr". But I want to access an array which is present in every object that is in "arr" i.e every object in "arr" has an array which has some elements in it. I want to access that array in my .ts file not HTML file. I need to do some modifications on that in .ts file so I want to know how do I create a pipe for the same.

I read that we need to use pipes.But I'm not understanding how do I use a pipe for this. If you can see in the picture there is a main array which has 3 objects and each of the 3 objects have an array called categories which again has objects. I want to access the field "category" inside categories for all the 3 objects present in the main array. Can someone help me do it ?

This is how my data looks


Solution

  • No need for pipes here, pipes would be used for actually displaying data in template, e.g if you would need to iterate object keys, which can not be used with *ngFor. But since you want to manipulate data in the component....

    You need two forEaches to reach every each category inside the different objects. And you need to do this from the callback (subscribe) after you have received the data, here's some more info on that: How do I return the response from an Observable/http/async call in angular2?

    I suggest you do the http requests in a service, and subscribe to the data in your component, so in your component, call that service method and subscribe to the response and then use forEach:

    ngOnInit() {
      this.service.getData()
        .subscribe(data => {
          this.searchResults = data;
          // call method or manipulate data here since response has been received
          this.manipulateData();
        });
    }
    
    manipulateData() {
        this.searchResults.forEach((x:any)=> { // iterate outer array
          x.categories.forEach((y:any) => { // iterate the categories of each object
            console.log(y.name) // ... or whatever properties you have
            // manipulate your data
          })
        })
    }
    

    DEMO