Combining various POST requests by matching the common value in each array. (Angular)

Here are the two different sets of data:

"statusCode": 200,
    "data": [
        {
            "color": {
                "id": "1111",
                "name": null,
                "hex": null,
                "image": "\/img\/.jpg",
                "subColors": [
                    {
                        "id": null,
                        "name": "White",
                        "hex": "#F5F4F8",
                        "image": null,
                        "subColors": []
                    },
                    {
                        "id": null,
                        "name": "Grey",
                        "hex": "#6c6f70",
                        "image": null,
                        "subColors": []
                    }
                ]
            },
            "articleVariants": [
                {
                    "id": "941282",
                    "articleNumber": "1000204445",
                    "size": "68\/74"
                }
            ]
        }
    ]

and

{
    "statusCode": 200,
    "data": [
        {
            "article": 1000204445,
            "ownStock": 3,
            "supplierStock": 18,
            "notice": null,
            "nextAvailability": null,
            "hasMoreOwnStock": false,
            "ownStockText": "3"
        }
    ]
}

The goal is to merge these responses based on the matching article numbers from "articleVariants.articleNumber" and the value of "article" from the second response.

This process aims to simplify the arrays for article numbers, where stock services can subscribe to these values, compare them with the requested article numbers, and return matching values mapped to the request.

If you have any tips on how to effectively merge these requests with the same values and map the new response accordingly, please share your insights as I am currently struggling with this task.

Answer №1

When working with Angular, leveraging ngrx can be incredibly beneficial for tasks like this.

To tackle your specific issue, consider utilizing combineLatest. Here's a basic example:

combineLatest(getStock(...), getArticleVariantsByColor(...)).subscribe(
    [stockResult, articleVariantsResult] => {
        /* Merge the results here to further process them
           such as assigning them to a component variable */
        const mergedItems = stockResult.data.map(stock => 
            articleVariantsResult.data.find(variant =>
                variant.articleVariants.include(articleVariant => 
                    articleVariant.articleNumber === stock.article
                )
            )
        )
    }
)

If my merging code doesn't meet your requirements, I simply wanted to showcase the use of combineLatest and accessing API results. Feel free to reach out if you encounter any challenges.

Answer №2

For the solution, let's break it down into 2 simple steps.

Initially, we will merge responses without involving Observables.

const response1 = {"statusCode": 200,
"data": [
    {
        "color": {
            "id": "1111",
            "name": null,
            "hex": null,
            "image": "\/img\/.jpg",
            "subColors": [
                {
                    "id": null,
                    "name": "White",
                    "hex": "#F5F4F8",
                    "image": null,
                    "subColors": []
                },
                {
                    "id": null,
                    "name": "Grey",
                    "hex": "#6c6f70",
                    "image": null,
                    "subColors": []
                }
            ]
        },
        "articleVariants": [
            {
                "id": "941282",
                "articleNumber": "1000204445",
                "size": "68\/74"
            }
           ]
        }
        ]
        };
const response2 = {
"statusCode": 200,
"data": [
  {
        "article": 1000204445,
        "ownStock": 3,
        "supplierStock": 18,
        "notice": null,
        "nextAvailability": null,
        "hasMoreOwnStock": false,
        "ownStockText": "3"
    }]};

var dataArray1 = response1.data;
var dataArray2 = response2.data;
const mergedResponse = dataArray2.map(d2 => ({...d2, 
...dataArray1.find(d1 => d1.articleVariants.find(av=>+av.articleNumber 
=== d2.article))}));
console.log(mergedResponse);

In the second step, we will utilize forkJoin to handle Observables efficiently.

const postResponse1 = of(response1);
const postResponse2 = of(response2);


forkJoin({
    response2: postResponse2,
    response1: postResponse1
})
.subscribe(({response2, response1}) => {
   var dataArray1 = response1.data;
   var dataArray2 = response2.data;
   const mergedResponse = dataArray2.map(d2 => ({...d2, 
      ...dataArray1.find(d1 => 
      d1.articleVariants.find(av=>+av.articleNumber === d2.article))}));
      console.log(mergedResponse);
});

Answer №3

If you're looking to streamline your code, consider using the forkJoin() method. Hopefully, this approach proves successful for you.

fetchData() {
     let requests = [this.articleVariantService.getArticleVariantsByColor(this.masterArticle.id,{},{}, this.language), this.stockService.getStock(itemNumbers)]
     forkJoin(requests).subscribe(data => {
     console.log(data[0], data[1]);
     let response = data;
  });
}

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

The local variable within the Angular constructor is not initialized until the ngOnInit() function is invoked

I am encountering difficulties with making backend calls from Angular. In my component, I am fetching the "category" parameter from the URL as shown below: export class ProductsComponent{ productList = [] category = "" $params; $products ...

Incorporate @ngx-translate into individual components within Angular 17 for enhanced translation capabilities

I have encountered an issue while using standalone components in Angular 17. Interestingly, when I used module architecture, this problem did not arise. By adding the necessary import to 'AppModule', everything worked perfectly. imports: [ Trans ...

Making if-else statements easier

Greetings! I have a JSON data that looks like this: { "details": { "data1": { "monthToDate":1000, "firstLastMonth":"December", "firstLa ...

Even when imperfections inevitably arise, flawless submission is always achieved

When working with a form that has a set minimum and maximum number of characters, I encounter an issue. If the minimum is set to 2 characters and I only input one character, I receive a mat-error message. However, upon clicking save, it allows me to procee ...

Incapable of acquiring the classification of the attribute belonging to the

Is it possible to retrieve the type of an object property if that object is stored in a table? const records = [{ prop1: 123, prop2: "fgdgfdg", }, { prop1: 6563, prop2: "dfhvcfgj", }] const getPropertyValues = <ROW extends o ...

When an Angular service is created, its properties are not immediately configured

My current task involves testing an Angular (4.1) service that looks like this: @Injectable() export class JobService { private answerSource = new Subject<AnswerWrapper>(); answer$ = this.answerSource.asObservable(); answer(answer: AnswerWra ...

Gridster2 for Angular: Resolving Overlapping Grid Items during Drag

The Angular version being used is 4.0.0 The angular-gridster2 library version being used is 2.10.0 When dragging the items randomly over other items, they become overlapped (as shown in the image below) The circled numbers represent the number of column ...

Getting TypeScript errors when incorporating a variant into a Material-UI button using a custom component

I have created a unique Link component inspired by this particular example. Take a look at the code below: import classNames from 'classnames'; import {forwardRef} from 'react'; import MuiLink, {LinkProps as MuiLinkProps} from '@ma ...

Structuring your Angular 6 application and server project

What is the recommended project structure when developing an Angular 6 application and an API server that need to share type definitions? For example: On the client side: this.httpService.get<Hero[]>(apiUrl + '/heroes') On the server si ...

Exploring data retrieval from nested arrays of objects in TypeScript/Angular

I have an API that returns an object array like the example below. How can I access the nested array of objects within the JSON data to find the role with roleid = 2 when EmpId is 102 using TypeScript? 0- { EmpId: 101, EmpName:'abc' Role : ...

Monitor checkbox status to trigger confirmation dialog

My goal is to prevent the checkbox from changing if 'NO' is clicked in a dialog. The dialog pops up, but I can't figure out how to wait for it to close before allowing the checkbox change. I've attempted using Promises and doing everyt ...

Issue "unable to use property "useEffect", dispatcher is undefined" arises exclusively when working with a local npm package

I am currently in the process of creating my very own private npm package to streamline some components and functions that I frequently use across various React TypeScript projects. However, when I try to install the package locally using its local path, ...

Using IONIC2 to localize month names in the UI

I am encountering a challenge with ionic2 related to translating month names into Portuguese for Brazil. In my views, I utilize the date filter to display the full month names, but they are currently appearing in English. I need them to be displayed in Bra ...

Is it possible for a component to accept another component as an input in Angular 2?

Important Reminder! Prior to implementing the technique mentioned in the answer, please review this discussion, which highlights the error Expression has changed after it was checked. Previous value: 'CD_INIT_VALUE'.. I have also shared a workar ...

Monitoring Node.js Server Events Triggered by Request and Response Objects

Currently, I am analyzing the logs of the application to provide you with important information regarding the two different strategies implemented within the system. POST Process PRE Process Under the first strategy, if the application needs to make a c ...

Strange Appearance of Angular Material Slider

I am experiencing some issues with my slider and I'm not exactly sure what's causing them. [] .big-container { display: block; padding-left: 10px; padding-right: 10px; padding-top: 10px; margin-bottom: 10px; } .question { display ...

What are the steps to resolve the MSB4132 error in MSBUILD on a Windows 10 system?

Currently working on an Angular 2 project while using Windows 10. When I ran npm install, I encountered this error message: MSBUILD : error MSB4132 MSBUILD : error MSB4132: The tools version "2.0" is unrecognized. The available tools versions are "12. ...

Error in Angular production build due to Clean CSS failure

Encountering the following error during the code build process, any solutions? > ng build --prod --no-aot --base-href 92% chunk asset optimizationD:\myproject\node_modules\@angular\cli\node_modules\clean-css\lib&bsol ...

What is the best way to store a small number of files in the state

I have recently implemented Drag and Drop functionality, and now I am facing an issue where I need to save a few files in state. const [uploadedFiles, setUploadedFiles] = useState<any[]>([]); const onDropHandler = async (e: React.DragEvent<HTMLDi ...

Navigating through a list using tabs and automatic scrolling to a specific index in React with Material UI's Scrollspy

If there was a vast array of items, each belonging to a specific category, const categories: string[] = [0, 1, 2, 3, 4, 5]; const items: {name: string, category: number}[] = [{name: "foo", category: 1}, {name: "bar", category: 1}, {name ...