What method is most effective for combining two JSON files in Angular?

My data includes a json file with a product list that looks like this:

[{"id":76,
  "name":"A",
  "description":"abc",
  "price":199,
  "imageUrl":"image.jpg",
  "productCategory":[{
    "categoryId":5,
    "category":null
   },{
    "categoryId":6,
    "category":null
   }
]}

In addition, I have another json file containing categories as follows:

[{"id":5,"name":"red"},
{"id":6,"name”:"blue"}]

I'm seeking the optimal approach to merge the category information from these two json files using Angular. Our end goal is to achieve the following result:

[{"id":76,
  "name":"A",
  "description":"abc",
  "price":199,
  "imageUrl":"image.jpg",
  "productCategory":[{
    "categoryId":5,
    "category":red
   },{
    "categoryId":6,
    "category":blue
   }
]}

Answer №1

I created a StackBlitz example that utilizes a service to fetch data. The method involves using switchMap and map. SwitchMap takes an array as input and must return an observable. Within the map function, we modify the received data before returning it.

this.dataService.getCategories().pipe(
         //first get the categories, which are stored in the
         //variable cats
         switchMap((cats:any[])=>{
           return this.dataService.getProducts().pipe(map((res:any[])=>{
               res.forEach(p=>{ //for each product
                 p.productCategory.forEach(c=>{ //for each productCategory in product
                   //assigns a property "category" with the value of "name" from the cats
                   c.category=cats.find(x=>x.id==c.categoryId).name 
                 })
               })
               return res
           }))
     })).subscribe(res=>{
       console.log(res)
     })

If there is only one unique product, we can simplify it to:

this.dataService.getCategories().pipe(
         switchMap((cats:any[])=>{
           return this.dataService.getUniqProduct(2).pipe(map((res:any)=>{
                 res.productCategory.forEach(c=>{
                   c.category=cats.find(x=>x.id==c.categoryId).name
                 })
               return res
           }))
     })).subscribe(res=>{
       console.log(res)
     })

We can enhance our dataService by implementing category caching:

  getCategories() {
    if (this.categories)
      return of(this.categories);

    return http.get(......).pipe(tap(res=>{
       this.categories=res;
    }))
  }

NOTE: In the StackBlitz example, I simulate the HTTP call using "of"

Answer №2

To fulfill your requirement, you can utilize the filter function as shown below:

let products = [{
      "id": 76,
      "name": "A",
      "description": "abc",
      "price": 199,
      "imageUrl": "image.jpg",
      "productCategory": [{
        "categoryId": 2,
        "category": null
      }, {
        "categoryId": 1,
        "category": null
      }]
    }, {
      "id": 77,
      "name": "B",
      "description": "abcd",
      "price": 1997,
      "imageUrl": "image.jpg",
      "productCategory": [{
        "categoryId": 5,
        "category": null
      }, {
        "categoryId": 6,
        "category": null
      }]
    },
    {
      "id": 78,
      "name": "C",
      "description": "abcde",
      "price": 1993,
      "imageUrl": "image.jpg",
      "productCategory": [{
        "categoryId": 4,
        "category": null
      }, {
        "categoryId": 6,
        "category": null
      }]
    }];


    let category = [{ "id": 5, "name": "red" }, { "id": 6, "name": "blue" }]

    let result = products.filter(p => {
      var exist = p.productCategory.filter(pc => category.find(c => c.id === pc.categoryId))[0];

      return exist;
    });

    console.log(result);

let products = [{
      "id": 76,
      "name": "A",
      "description": "abc",
      "price": 199,
      "imageUrl": "image.jpg",
      "productCategory": [{
        "categoryId": 2,
        "category": null
      }, {
        "categoryId": 1,
        "category": null
      }]
    }, {
      "id": 77,
      "name": "B",
      "description": "abcd",
      "price": 1997,
      "imageUrl": "image.jpg",
      "productCategory": [{
        "categoryId": 5,
        "category": null
      }, {
        "categoryId": 6,
        "category": null
      }]
    },
    {
      "id": 78,
      "name": "C",
      "description": "abcde",
      "price": 1993,
      "imageUrl": "image.jpg",
      "productCategory": [{
        "categoryId": 4,
        "category": null
      }, {
        "categoryId": 6,
        "category": null
      }]
    }];


    let category = [{ "id": 5, "name": "red" }, { "id": 6, "name": "blue" }]

    let result = products.filter(p => {
      var exist = p.productCategory.filter(pc => category.find(c => c.id === pc.categoryId))[0];

      return exist;
    });

    console.log(result);

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

Is it possible to efficiently share sessionStorage among multiple tabs in Angular 2 and access it right away?

My Current Knowledge: I have discovered a way to share sessionStorage between browser tabs by using the solution provided here: browser sessionStorage. share between tabs? Tools I Am Using: Angular 2 (v2.4.4) with TypeScript on Angular CLI base The ...

The cdkDragMoved event now provides the pointerPosition using the clientX and clientY coordinates rather than the container

I'm currently working on retrieving the x and y coordinates of a box based on its position within the container. Here's an example that I found on https://material.angular.io. To see how the cdkDragMoved event works, you can check out my small d ...

The JavaScript code snippets are ineffective, yielding an error message of "resource failed to load."

<? echo '<html> <script language=javascript> function validate() { alert("validate"); document.form1.action="validate.php"; document.form1.submit(); return false; } function del() { alert("delete"); document.form ...

Unspecified binding in knockout.js

As a newcomer to JS app development, I am currently focused on studying existing code and attempting to replicate it while playing around with variable names to test my understanding. I have been working on this JS quiz code built with KO.js... Here is my ...

How to efficiently retrieve data from a JSON file stored on an SD Card and showcase the information on a textview using Android?

I have a text file stored in my SdCard and I want to parse it using a Json parser. Once parsed, I would like to display the data in my textview. How can I achieve this? { "data": [ { "id": "1", "title": "Farhan Shah", "duration ...

Troubleshooting problems with Android web service communication using JSON

I am working on integrating JSON into my Android app. After following some tutorials, I managed to get the app reading test data from Twitter. package com.or.jsonswitch; import *** public class JsonTestMySwitchActivity extends Activity { /** This metho ...

Creating a file logging system with console.log() in hapi.js

I have recently developed an Application with Hapi.js and have utilized good-file to record logs into a file. However, I am facing an issue where the logs are only written to the file when using request.log() and server.log() methods. My goal is to also lo ...

best practices for choosing items from a dropdown menu using Angular

I have a dropdown list displaying existing tags/chips created by users in the past. However, I'm having an issue where when I select a tag from the dropdown list, it doesn't show up in my input field (similar to the Chart tag currently). I am abl ...

Having issues with my JavaScript code - it just won't function

I am having an issue with my JavaScript code. I don't receive any errors, but when I click the submit button, nothing happens. I have followed a video tutorial and watched it twice, but I can't seem to figure out what is wrong here. Here is the ...

Applying styles to every tr element in Angular 2 components

I'm trying to use background-color with [ngClass] on a table row. The styles are being applied, but they're affecting all rows' backgrounds. I want the background color to only change for the specific row that is clicked. Here is my code: ...

Unable to interact with the page while executing printing functionality in

component: <div class="container" id="customComponent1"> New Content </div> <div class="container" id="customComponent2"> different content </div> ...

NuxtJS using Babel 7: the spread operator persists in compiled files

Struggling to get my NuxtJS app functioning properly on IE11. Despite multiple attempts to configure Babel for compatibility, spread operators are still present in the built pages files, suggesting that Nuxt code is not being transformed correctly. Below ...

Tips for resolving the undefined error in TypeScript and React

Hey, I have this code snippet below which includes a call to the isSomeFunction method that returns true or false. However, there are times when the argument can be undefined. I only want to execute this function if selectedItems is not undefined. How can ...

While the Navbar component functions properly under regular circumstances, it experiences difficulties when used in conjunction with getStaticProps

https://i.stack.imgur.com/zmnYu.pngI have been facing an issue while trying to implement getstaticprops on my page. Whenever I try to include my navbar component, the console throws an error stating that the element type is invalid. Interestingly, I am abl ...

The process of parsing JSON to send a verification code from the server to email is experiencing technical difficulties

Consider the following code snippet : @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.register); emailto= (EditText)findViewById(R.id.editText3 ...

The React function is encountering a situation where the action payload is not

I encountered an error stating Cannot read property 'data' of undefined switch (action.type){ case REGISTER_USER: console.log("Action ", action);// This prints {type: "REGISTER_USER", payload: undefined} return [action.payload.data, ...

Effect fails to activate on the third occurrence of the action

After successfully running on the first two action dispatches, the effects fail to trigger on the third time. I have tried the solutions provided in this thread and here, but none of them work for me. Here is the relevant code snippet: @Effect() get ...

Utilizing enum values in the HTML value attribute with Angular 2

I'm attempting to utilize an enum value in order to set the selected value of an HTML attribute: export enum MyEnum { FirstValue, SecondValue } export function MyEnumAware(constructor: Function) { constructor.prototype.MyEnum = MyEnum; } ...

Is it possible to accept a number in string format in the request body?

I have a specific API spec that outlines the parameter account_id as being a string within the request body. If a request is received with a value for this field either as a number or even a boolean, such as: "account_id": 1234567890 or "account_id": t ...

What is the process for discovering the kinds of models that can be generated with a Prisma client?

Ensuring data type correctness when creating a Prisma model named 'bid' is crucial. With auto-generated prisma types available, understanding the naming convention and selecting the appropriate type can be confusing. The bid schema looks like th ...