Filtering nested JSON in Angular 8 to create a new array of results

Within the function fetchdataFromAPI, I am receiving JSON data from an API response.

My goal is to identify unique regions among all child objects in the JSON and create a new filtered array of objects that match my expected output.

I have attempted to retrieve the desired output using the code below, but it only returns objects from the first set of children, not all child objects.

I would appreciate assistance in correcting my code to achieve the expected response from the function provided.

fetchdataFromAPI() {
    const data = [
      {
        "name": "Africa",
        "children": [
          {
            "name": "Test1",
            "region": "1UL Africa"
          },
          {
            "name": "Test2",
            "region": "South Africa",
          },
          {
            "name": "Test3",
            "region": "1UL Africa"
          }
        ]
      },
      {
        "name": "Europe",
        "children": [
          {
            "name": "Test4",
            "region": "1UL Africa"
          },
          {
            "name": "Test5",
            "region": "Test Europe"
          }
        ]
      }
    ];
    this.dataService.setBUSubRegionList(this.processRegion(data));
  }

 processRegion(buRegionList) {    
    const list = [];  
    for (const buReg of buRegionList) {
      const tempBu = buReg;
      if (buReg.children) {
        let i = 0;
        for (const buRegion of buReg.children) {        
          if (!buRegion.region) {          
            tempBu.children.splice(i, 1);
          }
          i++;
        }
      }
      list.push(tempBu);
    } 
    return list;
  }

The expected output based on the provided JSON is as follows:

newData = [
   {
      "name": "Test1", 
      "region": "1UL Africa"        
   },
   {
      "name": "Test2",
      "region": "South Africa",           
   },
   {
      "name": "Test5",
      "region": "Test Europe"       
   },
];

Answer №1

Option 1

Upon reviewing the provided code, it seems that no filtering was performed and the filtered data was not added to the returned list.

function processRegion(buRegionList: any[]) {
    const list = [];

    for (const buReg of buRegionList) {
        if (buReg.children) {
            for (const buRegion of buReg.children) {
                if (list.findIndex(x => x.region == buRegion.region) == -1) {
                    list.push(buRegion);
                }
            }
        }
    }

    return list;
}

Demo Option 1 @ Typescript Playground


Option 2

Additionally, you can utilize .reduce() method to group by region as key-value pairs and then extract the values from these pairs into a list.

function processRegion(buRegionList: any[]) {
    const list = buRegionList.reduce((acc, cur) => {
        for (let child of cur.children) {
            if (!(child.region in acc)) {
                acc[child.region] = child;
            }
        }
        
        return acc;
    }, {});

    return Object.values(list);
}

Demo Option 2 @ Typescript Playground

Answer №2

Check out the solution on stackblitz

function extractUniqueRegionsFromList(buRegionList) {
    const uniqueList = [];
    buRegionList.forEach((eachList) => {
        (eachList.children).forEach((childData) => {
            const existingIndex = uniqueList.findIndex(
                (item) => item.region === childData.region
            );
            if (existingIndex === -1) uniqueList.push(childData);
        });
    });
    return uniqueList;
}

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

Leveraging _.some in lodash

I'm working on a Typescript code where I need to check if any items in one array are present in another array. Although I am new to lodash, I thought of using _.some for this task. However, the code is currently returning false when I expected it to r ...

Cross-site communication with Ajax using both POST and GET requests

As a beginner in JavaScript, I'm facing challenges with implementing ajax POST and GET requests. While I can successfully do it using Google Postman as shown here https://i.sstatic.net/Cegxj.pnghttps://i.sstatic.net/ovJT0.png, the problem arises when ...

Node Express is not designed to manage concurrent requests

Recently, I set up a NodeJS Express server in order to delve deeper into the inner workings of NodeJS. During my exploration, I discovered that NodeJS has the capability to efficiently handle numerous API requests simultaneously, as long as CPU intensive t ...

Properly configuring paths in react-native for smooth navigation

When working on my React-Native project, I noticed that my import paths look something like this: import { ScreenContainer, SLButton, SLTextInput, } from '../../../../../components'; import { KeyBoardTypes } from '../../../../../enums ...

Unable to transfer JavaScript values to PHP server

I am trying to retrieve values from a MySQL database and populate a table based on the user's selection from a dropdown. However, I am facing an issue where the selected value is not being sent to the server. Below is the code snippet: Code to fetch ...

"Utilize ajax and a modal window to insert a new record

Unable to retrieve values from ajax request when trying to add records using modal. (home.php) <script type="text/javascript> function saveData(){ var modsubj = $('#modalsubject').val(); var modsect = $('#modalse ...

Node accurately handles and displays errors, such as validation errors, in a precise manner

I am currently restructuring our code base to incorporate promises. Below are two blocks of sample code: user.service.js export function updateUserProfileByUsername(req, res) { userController.getUserByUsername(req.params.username) .then((userProfile ...

Playing videos with ReactJS: Learn how to implement a feature where a video is displayed in the center of the screen

I have a list of 20 items in my maplist, which are actually 20 videos. My goal is to play the video that appears in the center of the viewport and pause all others, maintaining this behavior while scrolling: const [reels, setReels] = useState([] ...

I'm encountering error code TS2314: The generic type 'ɵɵDirectiveDeclaration' is requesting 6 type arguments. How should I go about resolving this issue?

https://i.sstatic.net/b4Y6d.png https://i.sstatic.net/CIDTm.png While working on my project, everything was running smoothly until I copied a template into another component. Suddenly, the new component failed to recognize Angular Material elements, caus ...

Hide the modal pop up once the message has been submitted on the server side

I'm working with a bootstrap modal pop up that contains various controls and a submit button. After successfully submitting, I need to close the pop-up. The code snippet below displays the message "Record Saved successfully." if (strMessage == "Succe ...

The serverSideTranslations function require an initial locale argument to be passed in order to properly set up localization data

Decided to post here as per the recommendation of next-18next developers. I'm encountering an issue with next-i18next after updating both i18next and nextjs. The error message states: Initial locale argument was not passed into serverSideTranslation ...

The 'BaseResponse<IavailableParameters[]>' type does not contain the properties 'length', 'pop', etc, which are expected to be present in the 'IavailableParameters[]' type

After making a get call to my API and receiving a list of objects, I save that data to a property in my DataService for use across components. Here is the code snippet from my component that calls the service: getAvailableParameters() { this.verifi ...

To enable the standard PayPal 'donate' button functionality, you can remove the submitHandler from jQuery Validate dynamically

I need to insert a PayPal donate button into the middle of an AngularJS donation form, specifically by nesting the PayPal generated form tags within the donation form tags. This donation form is utilizing an older version (1.12) of jQuery Validate, which ...

Polyfill for window.showOpenFilePicker function

Could anyone recommend a polyfill for the window.showOpenFilePicker method? For reference, you can check out the documentation on MDN. ...

Struggling to append additional fields to a JSON string in PHP and seeking a solution

Looking to save a significant amount of data from a platform with very limited memory space. To workaround this issue, I'm storing the data on my webserver by using a PHP script to write JSON to a flat file. It may not be the most efficient method, bu ...

Updating new objects in Angular using JavaScript Object-Oriented Programming may not be working

Recently delving into OOP in JavaScript while working on an AngularJS website, I encountered a situation where my object methods were only altering the properties within the class, but not affecting the new object itself. //Class Var Item = function() { ...

An error was encountered: Module "@angular-devkit/build-angular" was not located within the "/project" directory when running into a docker container

In my attempt to get an image in docker where I can simply run docker-compose up --build and the container works, I encountered a hurdle. After building the image, I faced an error when I executed docker-compose up: An unhandled exception occurred: Could ...

"Validation with Express-validator now includes checking the field in cookies instead of the request

My current validator is set up like this: const validationSchema = checkSchema({ 'applicant.name': { exists: true, errorMessage: 'Name field is required', }, }); and at the beginning of this route (the rest is not relevant) ...

Setting dynamic tab titles using JSON in an Android application written in Java

I am working with a JSON API to retrieve the dates of Yesterday, Today, and Tomorrow. I have a swipe menu with three tabs, and I want the title of each tab to display the respective date (Yesterday's date for the first tab, etc.). After successfully ...

Concealed component with a one-second pause

Is there a way to dynamically hide a div element based on certain conditions in an option list? I am currently using jQuery for this purpose. if ($("#prov").val() == "0") { $("#label1").hide(); $("#list1").hide(); } else { $("#l ...