Angular – Loop through response, get a specific value and pass it as a parameter to a func

Issue

0:
description: "desc"
filter: "{equal: '3'}"
filter_name: "desc"
id: 1
pages: [{…}]
1:
description: "descc"
filter: "{equal: '4'}"
filter_name: "descc"
id: 2
pages: [{…}]

Above is my response i logged into console. I need to loop through this response and get each filter value. Then, i will pass this values to a function.
Something like this :

   this.service.getFilters().subscribe((response : any) => {
          //foreach response
          //get filter value ({equal: '3'})
          function(filter value here)

      }) 

Solution

Iterate over response:

this.service.getFilters().subscribe((response : any) => {
    response.forEach( item => {
        function(item.filter) // your function that handles each filter separately
    })  
}) 

If you actually need to send all filters together, you can do like this:

this.service.getFilters().subscribe((response : any) => {
    let allFilters = [];
    response.forEach( item => {
         allFilters.push(item.filter);
    }) 
    function(allFilters) // your function that handles all filters as an array
}) 

Answered By – Misha Mashina

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.