How to filter nested JSON children objects and return result Angular 8

Viewed 52

I am getting API response inside filterchildrenByRegion() function,

I want to remove those object which are not matching with the selected Region and return all data as it is.

Ex 1 - If i will pass '1UL Africa' inside changeRegion() function,than it will return data as my expected output 1.

Ex - 2 - If i will pass 'South Africa"' inside changeRegion() function,than it will return data as my expected output 2.

changeRegion(){  
 this.newRegion = this.filterchildrenByRegion('1UL Africa');
}

 filterchildrenByRegion(region){      
   this.data = [
      {
        "name": "Africa",
        "children": [
          {
            "name": "Test1",
            "region": "1UL Africa"
          },
          {
            "name": "Test2",
            "region": "South Africa",
          },
          {
            "name": "Test3",
            "region": "New Test",
          }
        ]
      },
      {
        "name": "Europe",
        "children": [
          {
            "name": "Test4",
            "region": "1UL Africa"
          },
          {
            "name": "Test5",
            "region": "Test Europe"
          }
        ]
      }
    ];    
      return this.data.filter(x => x.children.map(child => child.region).includes(regionName));
  }; 

Expected OutPut1

 result =  this.data = [
      {
        "name": "Africa",
        "children": [
          {
            "name": "Test1",
            "region": "1UL Africa"
          }
        ]
      },
      {
        "name": "Europe",
        "children": [
          {
            "name": "Test4",
            "region": "1UL Africa"
          }
        ]
      }
    ];

Expected OutPut 2

 result =  this.data = [
      {
        "name": "Africa",
        "children": [
          {
            "name": "Test1",
            "region": "1UL Africa"
          }
        ]
      }     
    ];
1 Answers

Here is a sample that will work for your case

return this.data.map((x) => {
        const childrenFulfillingTheSearch = x.children.filter(c => c.region.includes(region));

        if (childrenFulfillingTheSearch.length === 0) {
          return undefined; //this country has no children fulfilling the requirements
        }

        return {
          ...x,
          children: childrenFulfillingTheSearch
        };
      })
      .filter(x => x !== undefined);

Click here to view a running example

Related