Filtering nested JSON objects of children using a specific value in Angular 8

Within the function filterchildrenByRegion(), I am receiving an API response.

My goal is to eliminate objects that do not match the selected Region and return all data as it is.

Example 1 - If I input '1UL Africa' into the changeRegion() function, it will produce the expected output 1.

Example 2 - If I input 'South Africa"' into the changeRegion() function, it will generate the 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 Output 1

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

I attempted the following code, but it returned an empty result:

getClusterObjectByRegion(regionName: string) {
    this.data = this.clusterFactoryList;
    return this.data.map((x) => {
      const childrenMatchingSearch = x.children.filter(c => c.buSubRegion.includes(regionName));
      if (childrenFulfillingTheSearch.length === 0) {
        return undefined;
      }
      return {
        ...x,
        children: childrenMatchingSearch
      };
    }).filter(x => x !== undefined);
  };

Expected Output 2

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

Answer №1

While maybe not the most sleek solution, this code snippet should fulfill your requirements if I have interpreted them accurately:

const filterByRegion = (region) => {
  return data.map(item => ({
    ...item,
    children: item.children.filter(child => child.region === region)
  })).filter(item => item.children.length > 0);
}

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

What is the best way to utilize useClient in the code of my Next.js project?

I've been attempting to execute the code attached below, but I keep encountering an error stating that a component being imported requires useState and should only be used in a Client Component. However, none of its parent components are marked with " ...

Automatically navigate to a specific element as the user scrolls down the page

I am attempting to achieve a similar effect as seen on the App Builder Website. When the user reaches the header with the background image/video and scrolls down, the website smoothly transitions to the next div/section. If the user scrolls back up and ret ...

Numerous pop-up windows displaying a variety of distinct content in each one

While working on a website, I came across a helpful jQuery pop-up function that I found on Stack Overflow. The original post can be found here. I am trying to customize each pop-up box so they contain different content from the .pop1 and .pop2 divs (parag ...

Using Javascript to parse a json file that contains additional content at the beginning

I am attempting to access a JSON URL, but the JSON is displaying some extra characters before it starts. The structure of the JSON script is as follows: throw 'allowIllegalResourceCall is false.'; { "name":"mkyong", "age":30, "addres ...

Converting dates in Javascript

I have retrieved a date/time value of "20131218" from an API response. My goal is to transform this date into the format "2013-12-18". In PHP, this can be easily achieved with the following code: echo date("Y-m-d", strtotime('20131218')); The ...

Converting Spark dataframe to ASCII-formatted JSON files

I'm currently working on saving a spark dataframe as a JSON file, which will be later stored in a MapR JSON DB table. grp_small.toJSON.write.save("<path>") It appears that this code saves the JSON file in snappy.parquet format. Is there a way ...

Check if a given string conforms to the JSONATA expression format

Here's the scenario: A user inputs a JSONATA expression into a form field. The form should show an error message if the entered JSONATA expression is invalid. Is there a regular expression or pattern that can determine the validity of a string as a ...

Generate an array of responses within a child component and then send this array to the parent component using Vue.js 2

Currently, I am in the process of creating a survey using Vue 2. My goal is to construct and emit the answers array to a parent component named Evaluation. You can view the structure of this array here: https://pastebin.com/rLEUh56a Within my project, the ...

Trigger a JavaScript function when a key is pressed down

Hey everyone, I'm trying to figure out how to trigger a JavaScript function when a particular key is pressed. For example, I want the function down() to be executed when the down key is pressed and function left() when the left key is pressed. Is ther ...

Adjusting the size of content tags depending on their popularity

Currently, I am working on setting up a basic tagging system by following the database structure provided in this Stack Overflow post. My goal is to create a single page that showcases all the tags, with each tag being visually scaled based on its popular ...

CustomJS TextBox callback to adjust range of x-axis: Bokeh

I'm currently working on a web page that features a plot powered by an AjaxDataSource object. However, I am facing a challenge with implementing a TextInput widget that can modify the xrange of this plot. Here is a snippet of my code: source = AjaxDa ...

How to Resolve jQuery Script Delay Caused by AJAX Request?

I am in the process of creating a unique responsive Wordpress Theme, with only one page that loads content via AJAX. Here is the AJAX function I have implemented: jQuery(document).ready(function(){ jQuery.ajaxSetup({cache:false}); jQuery(" ...

Purging and Rebooting Material Selection

Despite the numerous questions on this topic, none of the solutions provided seem to be effective for my particular issue. In my Angular application, I have a series of interconnected mat-select elements. The selection made in one mat-select influences th ...

Angular 4: Is there a correlation between the level of complexity in componentizing HTML and the difficulty of passing variables to sibling components?

Do you ever wonder if the way you're approaching something is correct? I tend to believe that breaking down an HTML page into as many sub-components as possible is a good practice. For example, let's look at this situation: An existing compone ...

Comprehending the significance of *this* within class structures

I've got this code snippet below. class Node { constructor(value, parent, possibleChildren = []) { this.value = value; this.parent = parent; this.children = [] this.setChildren(possibleChildren); } setChildren(possibleChil ...

Encountering an unexpected identifier error in Sails JS

As a newcomer to Sails JS, I am attempting to perform CRUD operations with it. However, I am encountering an unexpected error in my index function. I am struggling to identify where the mistake lies. // Usercontroller.js file module.exports = { creat ...

How can TypeScript leverage the power of JavaScript libraries?

As a newcomer to TypeScript, I apologize if this question seems simplistic. My goal is to incorporate JavaScript libraries into a .ts file while utilizing node.js for running my program via the console. In my previous experience with JavaScript, I utilize ...

What is the best way to transfer data from one worker to all the others in node.js?

Upon node boot up, I initialize an in-memory JavaScript object. This node app runs on multiple cores using the cluster module. When an HTTP request is received, it is handled by one of the worker threads which then modifies the value of the JavaScript ob ...

Ensuring each div element has a unique bullet icon: A step-by-step guide

I am looking to dynamically create bullet icons based on the number of div elements present in a slider. For instance, if there are 2 slider divs, I want to generate 2 bullet icons within another div. If there are no div elements, then the bullets should ...

Modify the label contents to reflect the selected file, rather than using the default text

Currently, I am working on customizing my file upload input to enhance its appearance. Everything is going smoothly so far, but I am facing difficulty in finding a suitable jQuery script that can meet my specific requirements. My objective is to have the ...