Utilizing Rxjs to transform an array of objects

My goal is to map an array of objects. Currently, I have the following code:

return this.service.post(url, payload, this.httpOptions)
    .pipe(
        map((obj: any, index) => [({
            ...obj,
            val1: obj[index].val1.id,
            val2: obj[index].val2.id
        })]
    ))

I've also tried approaching it in a different way:

  map((obj: any, index) => 
        {   
            const list = []
            const newObj = { 
                ...obj,
                val1: obj[index].val1.id,
                val2: obj[index].val2.id
            }
            list.push(newObj);
            return list;
        }

Input:

 [
  {
    "val1": { "id": "USER_ID", "value": "User1" },
    "val2": { "id": "USER_ID", "value": "User2" },
    "val3": "aaa",
    "val4": "val2"
  },
  {
    "val1": { "id": "USER_ID", "value": "User3" },
    "val2": { "id": "USER_ID", "value": "User4" },
    "val3": "dds",
    "val4": "eee"
  }
]

Expected output:

   [
    {
      "val1": "USER_ID",
      "val2": "USER_ID",
      "val3": "aaa",
      "val4": "val2"
    },
    {
      "val1": "USER_ID",
      "val2": "USER_ID",
      "val3": "dds",
      "val4": "eee"
    }
]

Currently, instead of an array of objects, I have an array with one object that contains all objects. My desired outcome is to have an array of objects where each object contains the original data plus the mapped values such as val1 and val2.

Answer №1

Your issue lies within the map() operator. It is receiving the entire payload instead of individual items, treating what you refer to as obj as an array. To resolve this, you must also apply .map() on the array.

Additionally, the index parameter is unnecessary since the property exists directly on the object itself.

    map(inputArray => inputArray.map(obj => ({
      ...obj,
      val1: obj.val1.id,
      val2: obj.val2.id
    }))

For a functional demonstration, check out this StackBlitz

Answer №2

When utilizing the .map() method on the response data, which is anticipated to be an array, the resulting output will also be an array. There is no need to re-encapsulate it within another array in the map callback function. As for the second requirement of adding additional key-value pairs to each element of the response, your current code using the spread operator is adequate. Consider implementing this modification for your map operation:

return this.service.post(url, payload, this.httpOptions)
    .pipe(
        map((obj: any) => {
          return {
            ...obj,
            val1: obj.val1?.id,
            val2: obj.val2?.id
         }
      })
   )

By following this approach, the desired output will be achieved as:

[ {key1: value, ..., val1: value, val2: value}, ... ]

To review a demonstration of the code, refer to: https://ideone.com/stVusF

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

Encountering errors while attempting to install TypeScript through NPM

I am encountering an issue while trying to install Typescript using npm. Following the documentation, I executed the command: npm install -g typescript or sudo npm install -g typescript - Everything seems to be going smoothly until it reaches about 2 ...

When attempting to open a form in edit mode, data binding fails to work across multiple form controls

When clicking on the edit button, data is loaded into the form using [(ng-model)], however, it seems to be working correctly only for some fields and not all fields. The data is displayed in only a few fields despite receiving data for all fields. Below is ...

Variable type linked to interface content type

Is it possible to link two fields of an interface together? I have the following interface: export interface IContractKpi { type: 'shipmentVolumes' | 'transitTime' | 'invoices'; visible: boolean; content: IKpiContent; } ...

Incorporating an external module into your Angular application for local use

I currently have two projects: my-components, which is an Angular library, and my-showcase, an Angular app. Whenever I make changes or add a new component to my library, I commit it to a private git repository and publish it to a private npm registry. This ...

Tips for troubleshooting TypeScript Express application in Visual Studio Code

Recently, I attempted to troubleshoot the TypeScript Express App located at https://github.com/schul-cloud/node-notification-service/ using Visual Studio Code. Within the launch.json file, I included the following configuration: { "name": "notifi ...

Before the user closes the window, Angular 2 makes an HTTP request

Whenever the user is about to close the window, I want to ensure that changes are saved. However, I'm facing an issue where the changes are not saved when I close the tab, even though it works fine when I refresh the page with F5. Below is the canDeac ...

Is it necessary to use ReplaySubject after using location.back() in Angular 6 to avoid requesting data multiple times?

I'm currently utilizing a BehaviorSubject in my service to retrieve data from the BackEnd, which I subscribe to in my mainComponent using the async pipe. However, whenever I navigate to another subComponent and then return to my mainComponent by clic ...

Remove an item from an array within Express using Mongoose

{ "_id": "608c3d353f94ae40aff1dec4", "userId": "608425c08a3f8db8845bee84", "experiences": [ { "designation": "Manager", "_id": "609197056bd0ea09eee94 ...

Incorporate my personalized icons into the button design of ionic 2 actionSheet

I'm struggling to figure out how to incorporate my personal icon into the actionSheet feature of ionic 2/3. presentActionSheet() { let actionSheet = this.actionSheetCtrl.create({ title: 'Mode', buttons: [ { ...

What is the method to incorporate a fresh generic parameter without officially announcing it?

My goal is to define a type union where one of the types extends an existing type: // The original type type Foo<V> = { value: V; onChange: (value: V) => void }; // Type union incorporating Foo type ADT = ({ kind: "foo" } & Foo<a ...

Issues encountered when integrating ag-grid-react with typescript

Despite extensive searching, I am unable to find any examples of utilizing ag-grid-react with TypeScript. The ag-grid-react project does have TypeScript typing available. In my React app, I have installed ag-grid-react: npm i --save ag-grid ag-grid-react ...

Move forward state using navigateByUrl in Angular

I am looking to send data when changing the view using navigateByUrl like this: this.router.navigateByUrl(url, {state: {hello: "world"}}); Once in the next view, my goal is to simply log the hello attribute like so: constructor(public router: Router) { ...

What is the process of mapping an array of object IDs in order to retrieve the corresponding objects associated with each ID

I currently have a specific collection that stores IDs referencing objects in a separate schema. If I'm working with an array containing these IDs, what is the best way to iterate through and retrieve the corresponding object? Although I've mad ...

Exploring the concept of data sharing in the latest version of Next.JS - Server

When using App Router in Next.JS 13 Server Components, the challenge arises of not being able to use context. What would be the most effective method for sharing data between various server components? I have a main layout.tsx along with several nested la ...

Sending information to ng-template in Angular6

I'm new to Angular 6 and I have a query. How can I pass data to an ng-template from ngFor? component.html <tr *ngFor="let user of data"> <td>{{user.id}}</td> <td>{{user.username}}</td> <td>{{user ...

Adjust the colors of two elements by clicking a button's onclick event

As stated in the title, I have a button in the books component. When this button is clicked, the color of a div within the books component and another div in the navbar component should change. - Below is the code for the books component : export class Bo ...

Ways to retrieve the most recent update of a specialized typing software

When attempting to run typings install in a sample project with the below typings.js file, I received a warning. How can we determine the latest version number and what does the number after the + symbol signify? { "globalDependencies": { "core-js ...

MatDialog displaying no content

I found this tutorial on how to implement a simple dialog. The issue I'm facing is that the dialog appears empty with no errors in the console. Even after making changes to my dialog.component.html or dress-form.ts, nothing seems to reflect in the o ...

Retrieving the ng-content from an ng-template within one component and passing it to another component

Although there are various approaches available, my preference is to utilize ng-template, ng-content, and the @ContentChild() decorator in a specific way inspired by the implementation of Angular Material components. In this scenario, I have defined two c ...

What steps should I take to resolve the issue of my endpoint failing to accept POST requests?

I am in the process of developing a customized API, with an endpoint that is specified as shown below: https://i.stack.imgur.com/sZTI8.png To handle the functionality for this endpoint, I have set up a Profiling Controller. Inside my controller directory ...