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

Obtain the filter criteria within the user interface of a Kendo grid

My Kendo grid looks like this: <kendo-grid [data]="gridData" [pageSize]="state.take" [skip]="state.skip" [sort]="state.sort" [filter]="state.filter" filterable="menu" (dataStateChange)="dataStateChange($event)" > In the ...

Exploring Angular 7: A guide to implementing seamless pagination with routing for fetching API data

I am new to Angular and I would like some assistance. I need to modify the Route URL http://my_project/products/page/3 when the page changes. The API server provides data through paging, with URLs structured like http://apiserver/product/[limet]/[offset] ...

Refreshing the page causes TypeScript Redux to lose its state

custom/reducer/shoppingReducer.ts import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { ShoppingReducerInitialState } from "../../types/reducer-types"; import { ProductItem, ShippingDetails } from "../../types/typ ...

Efficient Searching with Typescript and Lodash: Boosting Performance with Arrays and Objects

I am faced with the challenge of converting between two classes called MyObject and MyObjectJSON, which have helper methods to assist in the conversion process: myObj.toJSON() and MyObject.fromJSON(). Currently, I have instances of these classes represent ...

Using Angular with adal-angular4 and implementing refresh token functionality

I have incorporated the Azure AD authentication in my Angular application using the package mentioned below: https://www.npmjs.com/package/adal-angular4 However, I am facing an issue where the token expires after 10-20 minutes. I have searched through va ...

Passing checkbox values using formgroup in Angular

I am a beginner in Angular and I need help with sending checkbox values within a formgroup. There are 2 checkboxes in the field, can someone assist me? masterList: { type: String, read: true, write: true }, eventlist:{ ...

Breaking down types in Typescript: Extracting individual types from an object containing multiple objects

Having a query: const queries = { light: { a... b... }, dark: { a... b... c... d... }, The react element requires a colors parameter that corresponds to one of the themes in the above object, with each theme containing a un ...

"Manipulating values in an array with a union type: a guide to setting and

I am currently working on creating an array that can have two different value types: type Loading = { loading: true } type Loaded = { loading: false, date: string, value: number, } type Items = Loading | Loaded const items: Items[] = ...

Passing asynchronous data from method1 to method2 without impacting the functionality of the script responsible for fetching the asynchronous data in method1

When working with TypeScript, I encountered an issue while trying to invoke an external script called SPCalendarPro within a private method that asynchronously fetches data. The script is invoked in the following manner: private _getSPCalendarPro() { con ...

Encountering a roadblock while trying to install a package using NPM, as the installation process becomes halted at version [email 

Having trouble installing @angular/cli via npm. It seems to get stuck every time while trying to download the package chokidar. https://example.com/image.png Here is some diagnostic information: npm version 5.0.0 node version 8.0.0 OS: Windows 7 ...

"Implementing a Filter for Selecting Multiple Options in Ionic Framework

I need help with filtering books in an online library project using a modal page. The modal has 3 input fields for title, author, and year. How can I filter the books based on these inputs? Here is a snippet of my modal.html code: <ion-content pa ...

TS2339 Error: The object 'Navigator' does not contain the property 'clipboard'

In the project I'm working on, there is an error that comes up when trying to copy custom data to the clipboard. It's something I can easily put together. Error TS2339: Property 'clipboard' does not exist on type 'Navigator' ...

How to easily scroll to the top of the previous page in Angular 8

In my Angular 8 application, there are buttons that are meant to take the user back to the previous page when clicked. While the functionality works as expected, I am facing an issue where the page does not automatically scroll to the top upon navigating ...

Determining the data type of a property within an interface using TypeScript

Is there a way to extract the type from an interface based on its property name in order to use it in a Record? I am struggling with the syntax needed to retrieve the type by property name. My goal is to make this process more future-proof so that if the i ...

Guide on creating a detailed list of categories mapped to specific classes that all adhere to a common generic standard

Most TypeScript factory patterns I've encountered rely on a named mapping between a name and the Class type. A basic implementation example: const myMap = { classOne: ExampleClass, classTwo: AnotherClass } (k: string) => { return new myMap[k] } ...

Encountering errors while setting up routes with Browser Router

When setting up a BrowserRouter in index.tsx, the following code is used: import './index.css'; import {Route, Router} from '@mui/icons-material'; import {createTheme, ThemeProvider} from '@mui/material'; import App from &ap ...

Using Angular 6's httpClient to securely post data with credentials

I am currently working with a piece of code that is responsible for posting data in order to create a new data record. This code resides within a service: Take a look at the snippet below: import { Injectable } from '@angular/core'; import { H ...

Undefined error when refreshing Angular page

One particular page on my forum-like website is causing issues with refreshing. In my project, users can log in, view their profiles as well as others'. However, when I refresh a profile page, no data loads from the server and an error appears in the ...

Managing tabular data in reactive forms in Angular

Currently, I am working on a calendar application where I need to manage three tabs within a form - hours timing, out of office, and holiday tabs. I am facing some challenges in efficiently grouping the form due to having only one form and button for event ...

I'm encountering an issue in my node application where it is unable to access the push

I am a beginner in the world of node.js and express. Whenever I try to start my application using the command npm start, I encounter an error message saying Cannot Read property push of undefined from my index.js file. The problematic code snippet looks l ...