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

Error Message: Unable to access properties of an undefined object while interacting with an API in a React application

Creating a Weather application in React JS that utilizes the OpenWeatherMapAPI to display dynamic backgrounds based on the API response. I need to access the data at 'data.weather[0].main' which will contain values like 'Clear', ' ...

The function error is currently in a waiting state as it already includes an

I encountered a particular issue that states: "await is only valid in async function." Here is the code snippet where the error occurs: async function solve(){ var requestUrl = "url"; $.ajax({url: "requestUrl", succes ...

The LinkedIn API encountered an error when attempting to retrieve historical follower data, resulting in a HTTP

I've scoured the depths of the internet in search of a solution to my problem, but none seem to fit what I need. My goal is to retrieve historical follower data from LinkedIn's API using this call: ${companyId}/historical-follow-statistics?time- ...

Encountered an error while handling a promise: Unable to access null properties (specifically, 'useState')

I'm having trouble understanding why I keep encountering this error with the line const [isLoading, setLoading] = useState(true);. It's initially set to true so it shouldn't be undefined. export default async function GetProducts() { c ...

Gradle synchronization in IntelliJ causing missing folders in WAR Artifact

Currently, I am working on a Spring MVC application that incorporates TypeScript. The TypeScript code is transpiled using a Gradle task from the directory src/main/ts to build/ts. Subsequently, the resulting JavaScript files are added to the WAR file usin ...

Encoding a multidimensional associative array into JSON using PHP

Having used php's json_encode() function frequently in the past, I am puzzled by the current issue... Note: Error checking has been omitted for clarity. //PHP <?php session_start(); require 'global/query.php'; $sql = "SELECT sfl,statio ...

A method for highlighting duplicate rows in a DataTable by formatting them with the same color

I am currently utilizing the DataTable plugin to display rows in a table. I would like to highlight duplicate rows in the same color scheme. Can someone please assist me with this issue? In the example below, the entry for Black Winters is duplicated. I ai ...

Error: Missing root tag after converting XML to JSON and saving it to disk

My goal is to develop a straightforward XML to JSON converter that reads from one folder and outputs to another. The conversion process appears to be functioning properly, but I am struggling to include the root tag of the XML in the output. Below are some ...

Activate jQuery after a vanilla JavaScript function has been executed

I have created a jQuery function that captures any changes made to an input field and stores them in a variable. The input field is connected to a vanilla JavaScript based API library, which I am unable to convert to jQuery. This library is for an address ...

Is Aurelia-Fetch reliant on whatwg-fetch as a dependency in its codebase?

I am currently in the process of updating my Aurelia project from a beta version to the March version. One of the issues I encountered is: Cannot locate name 'Request'. Searching online led me to this problem on GitHub: https://github.com/au ...

The connection between the type of request and the corresponding response in an Ajax function

When using the following: xhr.setRequestHeader("Content-Type", "application/json"); Am I obligated to only receive a response in json format, or is it possible to receive an html response instead? If there is flexibility in receiving different formats, h ...

Adding a div beside an input element - step by step guide

When creating an input field in my code, I followed these steps: var inputVal = document.createElement("input"); inputVal.setAttribute("type", "checkbox"); inputChek.onchange = select; inputChek.setAttribute("value", title); //inputChek.after(sortDiv); ...

The switch/case function I implemented is functioning correctly, however, an error is being displayed in the console stating "Cannot read property 'name' of null"

Check out the live codepen demo here After selecting "elephant" from the third dropdown, the console.log(brand.name) displays "elephant" as expected and executes the rest of the switch statement successfully. However, there seems to be a console error oc ...

How jQuery manipulates the DOM during a drag-and-drop operation

My current challenge involves implementing jquery-ui sortable on items that appear while scrolling. Below is the code snippet I am using: var gridTop = 0, gridBottom = container.outerHeight(); $('#play-list').on('scroll', ...

How can we efficiently determine if any of the keys in an array of objects contains a value that is present in another array of arrays object?

I am working on developing a filtering system that checks for the existence of project technologies in the arrOfObjs.name. If a match is found, then the filter will allow the project to be displayed in the DOM. This filter specifically involves using a com ...

Incorporating multiple true statements into an IF ELSE structure can enhance the decision-making

I'm struggling with getting a true return value for numbers that are integers and have either 4 or 6 digits - no decimals or letters allowed. The issue seems to be the validation of whether it's really a number and if it has a decimal point. Alt ...

Conceal the div element if the value exceeds 0

I'm looking for a way to display a div when the number of remaining days is less than 0. I got it working on jsfiddle, but for some reason, it doesn't work anywhere else. if ($('.daysrem&a ...

Struggling with getting my Vue-CLI app deployed on Heroku

After diligently following all the steps outlined in this tutorial: https://codeburst.io/quick-n-clean-way-to-deploy-vue-webpack-apps-on-heroku-b522d3904bc8 I encountered an error message when checking my app at: The error indicated: Method Not Allowed ...

Utilizing Vue CLI's sourcemaps to pinpoint the styling within a Vue component file

Currently, I am working on a Vue CLI project. After setting up the project and making some development changes, my package.json file now includes: package.json "dependencies": { "bootstrap": "^4.3.1", "core-js": "^3.0.1", "preload-it": "^1.2. ...

How to extract Network Content displayed in Chrome using file_get_contents in PHP

While browsing through a website on Chrome, I noticed that one of the items loaded in the network tab of ChromeDev Tools is a JSON file. I tried using file_get_contents to retrieve this JSON file but all it returned was the HTML content of the webpage. I ...