Enhance the API response for Angular service purposes

I am currently working on modifying the response returned by an API request. At the moment, I receive the response as:

[
   {
       name: "Afghanistan"
   }, 
   {
       name: "Åland Islands"
   }
]

My goal is to adjust it to:

[
   {
        name: "Afghanistan",
        name1: "Afghanistan",
        name2: "Afghanistan"
    },
    {
        name: "Åland Islands",
        name1: "Åland Islands",
        name2: "Åland Islands"
    }
]

I am attempting to duplicate the 'name' field and create new fields such as 'name1', 'name2' within the same object. Here is a functional project https://stackblitz.com/edit/angular-8bzcdp. Can anyone provide assistance?

Answer №1

If you want to update your approach, consider modifying your method like so:

  fetchData() {
    return this.http.get('https://restcountries.eu/rest/v2/all').pipe(
      map((res: any[]) => {
        const modifiedData = res.map(obj => ({
          name: obj.name,
          name1: obj.name,
          name2: obj.name
        }));
        return modifiedData;
      })
    );
  }

In this solution, each element in the resultant response array (res[]) is transformed into a JSON object according to your specifications before being returned as the newly created JSON object.

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

Circular dependency situation encountered in Angular 2 shared module

I'm currently working on a share module setup that is structured as follows: @NgModule({ exports: [ CommonModule, HttpModule, OneModule, TwoModule ] }) export class SharedModule { } The OneModule imports the SharedModule in order ...

Guide to configuring a function to display the maximum value on a boxplot in Highcharts

I'm currently using Angular in combination with the highcharts boxplot API. While I am aware that I can manually set the max value of the y-axis in the chart configuration, such as: max: 100, tickInterval: 10. There's now a need for me to dynami ...

The incorrect child output is causing the observable to trigger erroneously, resulting in the observable receiving inaccurate

For quite some time now, I've been struggling to identify the issue in my code. The scenario is that I have a child component acting as a modal, which includes a search bar. When the user interacts with the search bar, it triggers an event to the pare ...

Is there a workaround for utilizing a custom hook within the useEffect function?

I have a custom hook named Api that handles fetching data from my API and managing auth tokens. In my Main app, there are various ways the state variable "postId" can be updated. Whenever it changes, I want the Api to fetch new content for that specific p ...

Looking to preview files on a server before downloading them? If you're getting the error message "Not allowed to load local resource: blob,"

Update: To clarify, we are using <embed #reportPdf width="100%" height="800"> and: this.pdf.nativeElement.src = this._window.URL.createObjectURL(this.re); It functions properly on Safari and Firefox. However, when loaded on Chrome, it displays as ...

Encountering the error message 'array expected for services config' within my GitLab CI/CD pipeline

My goal is to set up a pipeline in GitLab for running WebdriverIO TypeScript and Cucumber framework tests. I am encountering an issue when trying to execute wdio.conf.ts in the pipeline, resulting in this error: GitLab pipeline error Below is a snippet of ...

Tips for transferring information between concatMap operators in RXJS in an Angular application

I am working with an observable pipe that looks like this: .pipe( concatMap(() => this.security.getUser()), tap((partyId) => { if (!partyId) { window.location.assign(`${environment.redirectURL1}/dashboard/login`); } }), concatMap( ...

What is the process for accessing getBoundingClientRect within the Vue Composition API?

While I understand that in Vue we can access template refs to use getBoundingClientRect() with the options API like this: const rect = this.$refs.image.$el.getBoundingClientRect(); I am now attempting to achieve the same using template refs within the com ...

Best Practices for Implementing Redux Prop Types in Typescript React Components to Eliminate TypeScript Warnings

Suppose you have a React component: interface Chat { someId: string; } export const Chat = (props: Chat) => {} and someId is defined in your mapStateToProps: function mapStateToProps(state: State) { return { someId: state.someId || '' ...

Error message in Angular: Unable to locate a differ that supports the object '[object Object]' of type 'object.' NgFor is only able to bind to iterables like Arrays

When making an API call in my Angular project, I receive the following JSON response: { "data": { "success": true, "historical": true, "date": "2022-01-01", "base": "MXN&quo ...

invoke the next function a different privateFunction within rxjs

I'm trying to figure out how to pass the resetPassword data to the _confirmToUnlock method in Typescript/RxJS. Here is my subscribe method: public invokeUnlockModal() { let resetPassword = { userName: this.user?.userName}; //i need to send this ...

Issue with TypeScript Declaration File in NPM module functionality

Recently, I've been working on developing a package for NPM. It's essentially a JSON wrapped database concept, and it has been quite an enjoyable project so far. However, I've been facing some challenges when trying to include declarations f ...

Unable to retrieve the request body with bodyParser

I am currently working on a NextJS React Application. Within my server/index.tsx file, I have the following code: import next from 'next'; import express from 'express'; import compression from 'compression'; import bodyParser ...

Error in Firebase Emulator: The refFromUrl() function requires a complete and valid URL to run properly

Could it be that refFromURL() is not functioning properly when used locally? function deleteImage(imageUrl: string) { let urlRef = firebase.storage().refFromURL(imageUrl) return urlRef.delete().catch((error) => console.error(error)) } Upon ...

Testing the functionality of an event through unit test cases

I'm currently working on writing unit test cases for the function shown below: selected (event:any) { let selectedValue = event.target.value.substring(0,3); this.seletedBatch = selectedValue; this.enableSubmitButton = true } My test cases are a ...

What steps do I need to take to resolve the issue with the coa npm library version 2.1

While working on my Angular project, I encountered an error in the console logs: Error: 404 Not Found - coa-2.1.3.tgz I have not listed this library in my package.json file and the latest version available is 2.0.2. I am unsure about what steps to take ...

Angular 7: Implementing a Dynamic Search Filtering System

I'm looking to create a versatile filter in Angular 7 that can perform search operations on any field across multiple screens. Custom pipe filters I've come across only seem to work with specific static fields, limiting their use. Let me provide ...

Is it possible to compile using Angular sources while in Ivy's partial compilation mode?

Error: NG3001 Unsupported private class ObjectsComponent. The class is visible to consumers via MasterLibraryLibModule -> ObjectsComponent, but is not exported from the top-level library entrypoint. 11 export class ObjectsComponent implements OnInit { ...

How to handle an already initialised array in Angular?

I came across an interesting demo on exporting data to Excel using Angular 12. The demo can be found at the following link: This particular example utilizes an array within the component TypeScript file. import { Component } from '@angular/core' ...

Adding total stars options seems to be causing issues with the star rating feature in the ng framework

I have implemented the ng-starrating library in my Angular project by following this link. It was working fine without specifying the totalstars option like this: <star-rating value="{{rate}}" checkedcolor="#000000" uncheckedcolor="#ffffff"> Howeve ...