Playing with an array of objects

How can we modify an array of objects in Angular Typescript by replacing certain values and adding new key-value pairs?

I need to swap the id value with memberId and then introduce a new key fullName that combines firstName and lastName.

Any suggestions or assistance would be greatly appreciated. Thanks!

#Current solution

 this.data = this.data.map((item) => {
              let id = item.memberId;
              return {
                ...item,
              }
            });

#Original Data

[
    {
        "id": 10017,
        "firstName": "Alexa",
        "lastName": "Rimura",
        "roleDisplay": "COVP,DVP Real Estate",
        "companyName": "MS",
        "title": "COO",
        "memberId": 1,
        "roleDto": [
            {
                "id": 6,
                "name": "COVP", 
                "isShow": true,
                "transactionRoleId": 9
            },
            {
                "id": 7,
                "name": "DVP Real Estate",
                "isShow": true,
                "transactionRoleId": 6
            }
        ],
        "transactionRoleList": "Architect, Construction Project Director"
    },
    {
        "id": 10018,
        "firstName": "Briana",
        "lastName": "Christoval",
        "roleDisplay": "Architect,Construction Project Director",
        "companyName": null,
        "title": null,
        "memberId": 2,
        "roleDto": [
            {
                "id": 8,
                "name": "Architect",
                "isShow": true,
                "transactionRoleId": 12
            },
            {
                "id": 9,
                "name": "Construction Project Director",
                "isShow": true,
                "transactionRoleId": 11
            }
        ]
    }
]

#Expected Output

[
    {
        "id": 1,
        "firstName": "Alexa",
        "lastName": "Rimura",
        "fullName": "Alexa Rimura" ,
        "roleDisplay": "COVP,DVP Real Estate",
        "companyName": "MS",
        "title": "COO",
        "memberId": 1,
        "roleDto": [
            {
                "id": 6,
                "name": "COVP", 
                "isShow": true,
                "transactionRoleId": 9
            },
            {
                "id": 7,
                "name": "DVP Real Estate",
                "isShow": true,
                "transactionRoleId": 6
            }
        ],
        "transactionRoleList": "Architect, Construction Project Director"
    },
    {
        "id": 2,
        "firstName": "Briana",
        "lastName": "Christoval",
        "fullName": "Briana Christoval",
        "roleDisplay": "Architect,Construction Project Director",
        "companyName": null,
        "title": null,
        "memberId": 2,
        "roleDto": [
            {
                "id": 8,
                "name": "Architect",
                "isShow": true,
                "transactionRoleId": 12
            },
            {
                "id": 9,
                "name": "Construction Project Director",
                "isShow": true,
                "transactionRoleId": 11
            }
        ]
    }
]

Answer №1

You're just a step away from completing this task. Make sure to update the id property and add the fullName property as shown below:

this.data = data.map((item) => {
  return {
    ...item,
    id: item.memberId,
    fullName: item.firstName + ' ' + item.lastName
  }
});

If you prefer, you can achieve the same result by using Pipes and mapping the Observable with an rxjs operator.

getMembers() {
  return this.http.get<any[]>('/assets/data.json')
    .pipe(
      map((items: any[]) =>
        items.map(item => {
          return {
            ...item,
            id: item.memberId,
            fullName: item.firstName + ' ' + item.lastName
          };
        })
      )
    );
}

Check out a Sample Solution on StackBlitz

Answer №2

Do you mean something like this?

this.responseData = this.responseData.map((element) => {
    return {
       ...element,
       id: element.memberId
    }
});

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

Unique constraint for Mongoose string schema attribute

Suppose you have the given schema in Mongoose; how does it impact the collection? import { Schema } from "mongoose"; export interface IString { property: string; } export const PriceOverhaulSchema = new Schema<IString>({ property: { t ...

Launching Angular Component in a New Tab

Is there a method for displaying an Angular component in a separate tab exclusively for printing? The new tab should have a clean layout without any interactive elements that are linked back to the Angular program. The goal is to facilitate a simple and ef ...

Using Rollup alongside @rollup/plugin-babel and Typescript: Anticipated a comma, received a colon instead

I've encountered a problem while working with Rollup 4: [!] RollupError: Expected ',', got ':' (Note that you need plugins to import files that are not JavaScript) src/index.ts (48:19) Although my Babel configuration appears to ...

What is the best way to integrate OAuth into a stateless REST API?

Is there a way to utilize OAuth statelessly on a node/express server without breaking the statelessness of my REST api while using Passport for transferring user information through sessions? ...

Is there a way to customize the default styles of Kendo UI for Angular?

Is it possible to customize the default datepicker styles to look like the design in the second image? https://i.sstatic.net/h8yfA.png https://i.sstatic.net/PfiSf.png ...

❴eslint_d❵ [eslint] Oops! It looks like there was an issue loading the 'import' plugin declared in your .eslintrc.js file

Recently, while using neovim for TypeScript development, I decided to upgrade eslint to version 8.28.0. However, upon opening neovim, I encountered an error. Despite several attempts to troubleshoot the issue, I have been unsuccessful in resolving it on my ...

Updating the hostbinding to dynamically add a class

Consider the given component below: @Component({ selector: 'my-component', templateUrl: './my-component.html', style: [` :host.isSticky { position: sticky; top: 0; } `], changeDetection: ChangeDetectionStra ...

There is no property called 'x' in type 'y'

Can anyone explain why TypeScript is telling me this: Property 'dateTime' does not exist on type 'SSRPageProps'.ts(2339) Looking at my code below, I have data-time typed. import React from "react"; import axios from "axi ...

Angular 16 HttpClient post request with asynchronous action

Here I am working on integrating JWT in Angular with a .Net Core API. When I start my Angular server and launch the application, I encounter the following scenarios: Attempting with correct credentials initially fails, but retrying allows it to work. Tryi ...

In the event that you encounter various version formats during your work

Suppose I have a number in the format Example "1.0.0.0". If I want to increase it to the next version, it would be "1.0.0.1" By using the following regex code snippet, we can achieve this perfect result of incrementing the version to "1.0.0.1": let ver ...

Error message "Uncaught in promise" is being triggered by the calendar function within the Ionic

Can someone assist me in creating a calendar feature for my app? My concept involves a button with text that, when clicked by the user, opens a calendar. However, I am encountering an error message: ERROR Error: Uncaught (in promise): TypeError: Cannot set ...

Obtaining a TemplateRef from a directive: The process explained

I am currently working on developing a structural directive that can insert a TemplateRef, although the actual TemplateRef is defined in a separate location. Situation There are times when I need to add custom content within an existing element, but due ...

Allow Nest.js server to receive binary files in the request body

Is there a way to retrieve the uploaded binary file data from the browser? While the Nest.js server application functions correctly with Postman, it throws a 400 error when the request is sent from the Google Chrome/Angular application. Any ideas on how ...

The call does not match any overloads in Vue when using TypeScript

What is the reason behind the occurrence of the error in the ID part of the query? This call does not have a matching overload. <template> <swiper-slide slot="list" v-for="(list, index) in list.banner" :key=" ...

Error encountered during compilation of a TypeScript file using tsc command in Terminal

Error encountered while running the TypeScript compiler: - Cannot find name 'IterableIterator' in core-js. - Cannot find name 'Iterable' in core-js. - Cannot find name 'PropertyKey' in core-js. - Cannot find name 'Symbol& ...

The 'autoComplete' property cannot be found within the 'IntrinsicAttributes & InputProps' type

I'm currently utilizing Typescript and React, but encountering the following error: Property 'autoComplete' is not found on type 'IntrinsicAttributes & InputProps'. This is how I am using the component: <Input ...

Creating a Download file popup in a Spring MVC application for an Angular front end

I am currently working on a project where I need to download documents generated by the system. To achieve this, I have created a controller class in my Springboot backend to send requests to the frontend. @RequestMapping(value = "/downloadDocument/{docId ...

Learning how to implement the "as" syntax in TypeScript

Currently tackling an angular project that is functioning flawlessly, yet encountering a linting test failure. Unfortunately, the information provided in this post did not offer much assistance. The error message I'm facing reads as follows: ERROR: C ...

Ionic 2 - renders an array of objects [object, object]

The following code snippet shows how I use array push: let results = this.allExercises[i]; this.dataArray.push(results); To pass data with navParams and navigate to a new page, I do the following: this.navCtrl.push(HomePage, { 'exercisesDone&ap ...

Ignoring TypeScript type errors in ts-jest is possible

Recently, I embarked on a journey to learn TypeScript and decided to test my skills by creating a simple app with jest unit testing (using ts-jest): Here is the code snippet for the 'simple app.ts' module: function greet(person: string): string ...