Looking to extract a single JSON array object from multiple array objects to easily consume in an API with JavaScript

1. The following JSON data is retrieved from another API, with country and flag displayed in separate Array objects

{
"data": [
            {
                "service": "Tourist Visa",
                "service_id": 2,
                "country_id": 2,
                "country_name": "Australia",
                "country_flag": "https://getset-visa.s3.amazonaws.com/images/flag/australia-flag.JPG"
            },
            {
                "service": "Tourist Visa",
                "service_id": 2,
                "country_id": 1,
                "country_name": "India",
                "country_flag": "https://getset-visa.s3.amazonaws.com/images/countries/Indian-Flag.png"
            },
            {
                "service": "Visa Services",
                "service_id": 3,
                "country_id": 1,
                "country_name": "India",
                "country_flag": "https://getset-visa.s3.amazonaws.com/images/countries/Indian-Flag.png"
            }
        ]
}

2. For better consumption in an API using JavaScript, I aim to restructure the data as follows. Each country's information will be in a separate array object containing country name, flag, and services array

{
  "data": [
    {
      "countryName": "Australia",
      "countryFlag": "https://getset-visa.s3.amazonaws.com/images/flag/australia-flag.JPG",
      "services": [
        {
          "serviceName": "Tourist Visa"
        }
      ]
    },
    {
      "countryName": "India",
      ":countryFlag": "https://getset-visa.s3.amazonaws.com/images/countries/Indian-Flag.png",
      "l "services": [
        {
          "serviceName": "Visa Services"
        },
        {
          "serviceName": "Tourist Visa"
        }
      ]
    }
  ]
}

Appreciate any assistance.

Answer №1

To simplify the data structure and extract relevant information, you can utilize Array#reduce along with Map.

const response = {
  data: [
    {
      service: "Tourist Visa",
      service_id: 2,
      country_id: 2,
      country_name: "Australia",
      country_flag:
        "https://getset-visa.s3.amazonaws.com/images/flag/australia-flag.JPG",
    },
    {
      service: "Tourist Visa",
      service_id: 2,
      country_id: 1,
      country_name: "India",
      country_flag:
        "https://getset-visa.s3.amazonaws.com/images/countries/Indian-Flag.png",
    },
    {
      service: "Visa Services",
      service_id: 3,
      country_id: 1,
      country_name: "India",
      country_flag:
        "https://getset-visa.s3.amazonaws.com/images/countries/Indian-Flag.png",
    },
  ],
};

const output = Array.from(response.data.reduce(
  (m, {country_id: id, country_name: countryName, country_flag: countryFlag, service: serviceName}) => (
    m.has(id)
      ? m.get(id).services.push({ serviceName })
      : m.set(id, { countryName, countryFlag, services: [{ serviceName }] }),
    m
  ),
  new Map()
).values());

console.log({data: output});

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 for an exported class to contain private members?

In node.js, all data is private unless explicitly exported. Although I haven't found a way to export an entire class in a different manner, my objective is to prevent the privateMethod() from being accessible outside of where the class is imported an ...

Troubleshooting: VBA 3D array looping not displaying complete results

In my current project, there are 4 scheduled payments tied to specific "contract" dates stored in tblPaySch. However, the actual payments received (stored in tblTrans) sometimes vary in amount and date. To address this discrepancy, I am working on an arra ...

The TablePagination component from Material Ui is not functioning properly with my specific array of objects

My TablePagination is not updating the rows on each page of my table and not even limiting the rows with the row filter. I suspect this may be due to the way I'm building the table using an array mapping like this: 0: [name: Robert, age: 15, ...

Having trouble getting @vercel/ncc to work, keeps throwing a "Module not found" error

Recently, I have been attempting to follow a tutorial on creating custom GitHub actions using JavaScript from here. The tutorial suggests using the @vercel/ncc package to compile code into a single file if you prefer not to check in your node_modules folde ...

unable to retrieve access-token and uid from the response headers

I am attempting to extract access-token and uid from the response headers of a post request, as shown in the screenshot at this https://i.sstatic.net/8w8pV.png Here is how I am approaching this task from the service side: signup(postObj: any){ let url = e ...

Using three.js to control the opacity and size of points

I have returned with question number two about points. My query this time revolves around changing the opacity from 0 to 1 and back within specific pixel distances from the emitter. var particleCount = 14, particles = new THREE.Geometry(), pMaterial = new ...

Is it possible to use Three.js camera lookAt function without any rolling?

In my game, there is a square level where a ball can roll around. I am trying to adjust the camera position so that it follows the ball but always looks at 0, 0, 0. Moving the camera x and z towards the ball's position gets me close, but as seen in th ...

How can I access my API by connecting Node.js to MongoDB remotely?

I have been working on developing an application using Node.js, Express, and MongoDB. I followed some teamtreehouse tutorials to set up Node.js and MongoDB on a Digital Ocean Server. However, when trying to access my API through various URL variations, I e ...

What could be causing the PHP JSON response to fail in sending the data array back to the AJAX jQuery request?

After making an ajax request to the PHP server, I am sending data from a form request and expecting to receive the same data back from the server for testing purposes. This will help me analyze the requests and responses between the client and the server. ...

Tips for Guaranteeing a Distinct Email and Username are Stored in MongoDB with Mongoose

db.UserSchema = new db.Schema({ user: {type:String, unique:true, required:true,index:true}, email: {type:String, unique:true, required:true,index:true}, password: {type:String, required:true}, phon ...

Having trouble retrieving JSON data from the covid19india API for my Android application with Volley

Looking to retrieve information from this particular file: final ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setMessage("Loading data..."); progressDialog.show(); StringRequest stringRequest = ...

Can we find a jQuery AJAX equivalent to the 'finally' block in regular JavaScript?

Is there an equivalent of Java's 'finally' in jQuery AJAX calls? I have this code snippet here. Inside my always, I intentionally throw an exception, but I want it to always proceed to the then() method. call.xmlHttpReq = $.ajax({ ...

Angular ngClass and ngIf directives failing to update upon alterations

In my current Angular project, I am working on a functionality where I need to dynamically change a class based on a variable without having to refresh the page. I have experimented with *ngIf/else and [ngClass] directives, which do work, but unfortunatel ...

Adjust Leaflet map size when the containing element is resized (Dash Plotly)

I am encountering some difficulties with dash-leaflet, particularly regarding its width when the parent container is resized. I am utilizing dash-resizable-panels to resize certain divs. Allow me to present a Minimal Reproducible Example (MRE) below: # pi ...

The functionality of JQuery .change() is limited to one occurrence

Here is my JavaScript code snippet: jQuery(document).ready(function(){ const select = $('...'); //select element const input = $('...'); //input element select.change(doSomething()); input.change(doSomething()); f ...

I am facing an issue where the PHP header redirection stops working after implementing event.preventDefault() on form submission

After successfully implementing jQuery in my signup page to handle and check the form fields, I encountered an issue where the header("location: ../****.php") no longer redirected me to another page upon clicking submit. Instead, it loaded the new page on ...

I have a desire to use Javascript to control CSS styles

Within the CSS code below, I am seeking to vary the size of a square randomly. This can be achieved using the Math.random() property in Javascript, but I am uncertain how to apply it to define the size in CSS. #square { width: 100px; height: ...

Setting up the ajax header and implementing a redirect

I have a simple node authentication app. My goal is to send a token in the header when redirecting to a URL. For example, when a user clicks on their profile, they should be redirected with a token so they can access that page. I've tried implementin ...

How can promises be used in place of executing multiple mongoose queries?

Looking for a solution to avoid nested callbacks in the following code: app.get '/performers', (req, res) -> conductor = require('models/conductor').init().model soloist = require('models/soloist').init().model ...

Shifting hues of colors on website based on geographical location

Working on a new project, I encountered an issue with two elements sharing the same class but displaying different color shades. Has anyone experienced this before and knows what could be causing it? UPDATE Here is an excerpt of the code: The Class: .su ...