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

Troubleshooting native web worker issues in Angular 11 - Addressing the Element Bug

After upgrading Angular to version 11, I encountered issues with utilizing web workers for heavy data processing in my project. Previously, I used webworkify-webpack (https://www.npmjs.com/package/webworkify-webpack), but it stopped working post-migration. ...

Angular is unable to bind with 'dragula' because it does not recognize it as a valid property of 'ul'

I've been attempting to incorporate dragula into my Angular 2 application, but I'm struggling to get it functioning. This is what I have added in my app.module.ts file: import { DragulaModule, DragulaService } from 'ng2-dragula/ng2-dragula ...

Leverage the power of TypeScript with knockout's pureComputed function

I am facing an issue with referencing the this object in a function called problem: const c = { f() { console.log("hi"); }, problem: ko.pureComputed(() => { return this.f(); }), }; [ts] The containing arrow function captures the glob ...

Transform a protractor screenshot into a PDF file

I'm currently working on a small Protractor code that captures screenshots, but my goal is to save these screenshots as PDF files. Below you can find the code snippet I have written. await browser.get(url); const img = await browser.takeScreenshot(); ...

Dealing with Angular can be frustrating at times, especially when you encounter errors like "TypeError: Cannot

Encountering an Error Message... ERROR TypeError: Cannot read properties of undefined (reading 'geoCoord') at Object.next (customers.service.ts:16:38) When assigning fixed values to "lon" and "lat" variables, like 51.1634 and 10.4477, the f ...

Determining the appropriate version of the types package for your needs

It has come to my attention that certain npm packages do not come with types included. Because of this, the community often creates @types/packagename to provide those types. Given that both are packages, how does one determine which version of the types ...

How can I choose an option in a dropdown field labeled as ejs-dropdownlist with WebDriver in an Angular web application?

After spending some time grappling with this issue, I managed to find a solution. The ejs-dropdownlist tag is present on a web page that is currently in the development stage using Angular. Here is the complete XPath for the dropdown I am attempting to i ...

Returning a 'never' type from a function in React using Typescript

Basically, I have a function that initiates the OAuth flow (redirecting to Google OAuth login page, for example): async function signIn() { // start OAuth flow } And let's say I want to use it in a useEffect hook like this: ... useEffect(() => { ...

There seems to be a mismatch in this Typescript function overloading - None of the over

Currently, I am in the process of developing a function that invokes another function with enums as accepted parameters. The return type from this function varies depending on the value passed. Both the function being called (b) and the calling function (a ...

using angular and firestore to grant public reading permission for a document

As a student developer, I recently integrated Firestore into my Angular app and encountered some challenges with the security rules. My goal: I want to display a Firestore document in an Angular view using template binding. The document should be visible ...

Creating a feature that automatically determines the data type of a value using the provided key

My object type has keys that map to different types: type Value = { str: string; num: number; }; I am working on creating a universal format function: const format = <K extends keyof Value>(key: K, value: Value[K]): string => { if (key === ...

Priority of Search Results in Ionic Search Bar

I have an array of items that I'll refer to as fruitArray. fruitArray = ['Orange', 'Banana', 'Pear', 'Tomato', 'Grape', 'Apple', 'Cherries', 'Cranberries', 'Raspberr ...

I'm having trouble getting any data to emit when I subscribe to a state service subject that stores a hovered element. What could I be missing?

I am currently working on a project that involves a calendar, a hover directive, and a stateful service for communication. Here's a simplified representation of my work so far: https://stackblitz.com/edit/stackblitz-starters-kvzyvy?file=src%2Fmain.ts ...

Encountering dependency tree issues while trying to install @angular/material

I'm running into an issue while attempting to install the @angular/material module. Every time I execute the command: $ npm install --save @angular/material npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! ...

Creating TypeScript object properties dynamically based on function arguments

One of my functions takes in a variable number of arguments and creates a new object with a unique hash for each argument. Can Typescript automatically determine the keys of the resulting object based on the function's arguments? For instance, I ha ...

Using React with TypeScript to ensure that at least one key of a type is not null, even if all keys are optional

Within my Typescript code, I have defined an event type that includes various time parameters: export type EventRecord = { name: string; eta: string | null; assumed_time: string | null; indicated_time: string | null; }; I also have a func ...

What is the best way to extract and retrieve the most recent data from an XmlHttpRequest?

Currently, I am using a web service that returns an SseEmitter to program a loading bar. The method to receive it looks like this: static async synchronize(component: Vue) { let xhr = new XMLHttpRequest(); xhr.open('PATCH', 'myUrl.co ...

Determine the output of a function based on the structure of the input parameter by mapping through a complex nested object

Trying to implement some intricate typing for a project I'm developing, and wondering if it's achievable with TypesScript. The project in question is a form generator based on schemas and promises, using Vue and TS. It handles UI rendering, vali ...

Looking for a method to call a child component's function through a click event triggered from the parent component?

How can I trigger a specific function in my child component from a click event in my parent component? Any assistance would be greatly appreciated! ...

Angular - CSS Grid - Positioning columns based on their index values

My goal is to create a CSS grid with 4 columns and infinite rows. Specifically, I want the text-align property on the first column to be 'start', the middle two columns to be 'center', and the last column to be 'end'. The cont ...