Add fresh data key and corresponding value into an array containing multiple objects

Inserting an accountId key and value into the this.membersForm.value object is the goal, while also setting the id to 0 and adding memberId: id to the this.membersForm.value.teamMembersDto object.

How can we achieve this task of inserting the accountId key and value into the object? Please refer to the expectedOutput for more clarity.

Any ideas on what might be causing the issue in the code?

#myCode

const accountId = this.data.accountId

this.membersForm.value.teamMembersDto = this.membersForm.value.teamMembersDto.map((item) => {
      let id = item.id;
      return {
        ...item,
        memberId: id,
        id: 0,  
      }
    });

#original data

 this.membersForm.value = {
    "id": 10011,
    "teamMembersDto": [
        {
            "id": 1,
            "firstName": "Marthy",
            "lastName": "Hills",
            "roleDisplay": "COVP,DVP Real Estate",
            "companyName": "Techmo",
            "title": "COO",

        },
        {
            "id": 2,
            "firstName": "Briana",
            "lastName": "Christoval",
            "roleDisplay": "Architect,Construction Project Director",
            "companyName": null,
            "title": null,
        }
    ]
}

#expectedOutput

{
    "id": 10011,
    "accountId:" 4,
    "teamMembersDto": [
        {
            "id": 0,
            "firstName": "Marthy",
            "lastName": "Hills",
            "roleDisplay": "COVP,DVP Real Estate",
            "companyName": "Techmo",
            "title": "COO",
            "memberId": 1,
        },
        {
            "id": 0,
            "firstName": "Briana",
            "lastName": "Christoval",
            "roleDisplay": "Architect,Construction Project Director",
            "companyName": null,
            "title": null,
            "memberId": 2,
        },

    ]
}

___________________second question

#data

{
    "id": 20018,
    "name": "yoyo",
    "description": "yoyoyo",
    "memberCount": 2,
    "accountId": 4,
    "status": "Active",
    "createOnString": null,
    "teamMembersDto": [
        {
            "id": 10090,
            "firstName": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82c3c6c3d1c6c3c6c2e5efe3ebeeace1edef">[email protected]</a>",
... (remaining text unchanged) ...      
            "fullName": "adasdas dasdas"
        }
    ],
    "teamTransactionDetailsDto": []
}

#exptectOutput

{
    "id": 20018,
    "name": "yoyo",
    "description": "yoyoyo",
    "memberCount": 2,
    "accountId": 4,
    "status": "Active",
    "createOnString": null,
    "teamMembersDto": [
        {
            "id": 10090,
            "firstName": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b6f7f2f7e5f2f7f2f6d1dbd7dfda98d5d9db">[email protected]</a>",
... (remaining text unchanged) ...
            "fullName": "adasdas dasdas"
        }
    ],
    "teamTransactionDetailsDto": []
}

Answer №1

Below is a simple script that I have written for you which may be helpful:

let information = {
  "id": 10011,
  "teamMembersDto": [
    {
      "id": 1,
      "firstName": "Marthy",
      "lastName": "Hills",
      "roleDisplay": "COVP,DVP Real Estate",
      "companyName": "Techmo",
      "title": "COO",
    },
    {
       "id": 2,
       "firstName": "Briana",
       "lastName": "Christoval",
       "roleDisplay": "Architect,Construction Project Director",
       "companyName": null,
       "title": null,
     }
   ]
}

information["accountId"] = 0 // this line adds a new item

information.teamMembersDto = information.teamMembersDto.map((object) => {
  let id = object.id;
  return {
    ...object,
    memberId: id, 
    id: 0
  }
});
console.log(information)

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

Is it compatible to use Typescript version 2.4.2 with Ionic version 3.8.0?

Is it compatible to use Typescript 2.4.2 with Ionic 3.8.0? $ ionic info cli packages: (C:***\AppData\Roaming\npm\node_modules) @ionic/cli-utils : 1.18.0 ionic (Ionic CLI) : 3.18.0 global packages: cordova (Cordova CLI) : not insta ...

Is there a way to align all child elements to the right side inside a multi-select checkbox dropdown list using Angular?

I am seeking assistance with the following scenarios: I have a multiselect dropdownlist using the ng-multiselect-dropdown control in Angular. The parent and child items are bound using the code below in the HTML file: <ng-multiselect-dropdown name=&qu ...

Is there a way to assign DTO to an entity within typescript?

For my current project, I am utilizing Vue with TypeScript and Axios to retrieve objects from the backend. Here is an example of the object type I am working with: class Annoucement { id!: string; description?: string; deal?: Deal; realty?: ...

The view fails to update when the object is modified

Within the acceptRequest function in child.component, the commissioner.requestAccepted property is set to false, and then the updated commissioner object is returned. Ideally, I want the button to be automatically removed from the view once the object is ...

Reactive Programming: Transforming an earlier value as it moves down the pipeline

In a recent project, I encountered an interesting scenario involving the execution of multiple requests in a pipe chain. This specific case revolves around the display of images within the quill text editor. The backend returns the content in the followin ...

Is there a way to specify the sequence in which Observables are subscribed to in Angular?

Working with API calls in a service.ts file has brought me some challenges. Here is the code snippet: //code getCars() { this.car = this.http.get(car_url) return this.car; } getTires() { this.tires = this.http.get(tires_url) return this.tires; } getSeat ...

Angular2 Error -- The server is unable to locate the resource at http://localhost:1595/angular2/http

Struggling with getting my first Angular2 app up and running. I keep encountering the error message "The server has not found http://localhost/angular2/http". All other Angular elements are functioning correctly, so it appears to be a problem specific to ...

Establish a connection between MongoDB and the built-in API in Next.js

I've been working on integrating a MongoDB database with the Next.js built-in API by using the code snippet below, which I found online. /api/blogs/[slug].ts import type { NextApiRequest, NextApiResponse } from 'next' import { connectToData ...

Refresh a Google chart without having to reload the entire page

I currently have a button that allows me to refresh the data on my page in case there is new data available through an API. Although this button successfully refreshes my datatable, it does not redraw the Google charts I have integrated into my project usi ...

The ReactJS Material Table Tree mode experiences delays when new row data is introduced

My Reactjs app utilizes the material-table widget within a component: render() { return ( <div> <Row> <MaterialTable title="Mon équipement" style={{ width: "100%", margin: "0%" }} ...

Using custom Components to accept HTML input

I have recently developed a custom component to arrange content within IonCardContent. It has been effective for my current requirements: interface ContainerProps { position?: string; content?: string, colour?: string; custClass?: string; } ...

Tips for effectively using ngOnChanges in Angular 2 to validate inputs without causing the 'Expression has changed after it was checked' error

I attempted to create my own custom component with basic validation using regex that can be passed as input to the component. There are two scenarios to consider: one where the form is initially empty (new item form) and another where data is already prese ...

Steps to resolve the issue with "Error: StaticInjectorError(AppModule)[NgbDropdown -> ChangeDetectorRef]"

My attempt at creating a web app using Angular resulted in successful compilation with no errors. However, upon execution, the browser displays a blank page accompanied by the following error message: ERROR Error: Uncaught(in promise): Error: St ...

Assigning IDs to Values in Angular 2

Here is the code snippet in question: <select [(ngModel)]=""> <option value="1">New York</option> <option value="2"Phoenix</option> <option value="3">Boston</o ...

The optional parameters could not be obtained

After reading through the Angular documentation, it seems that I should be able to retrieve a route's options parameters from route.paramMap. However, when I attempt to log out the params, I am getting an empty object in return. I am developing a log ...

What is the approach to forming a Promise in TypeScript by employing a union type?

Thank you in advance for your help. I am new to TypeScript and I have encountered an issue with a piece of code. I am attempting to wrap a union type into a Promise and return it, but I am unsure how to do it correctly. export interface Bar { foo: number ...

What could be causing the strange output from my filtered Object.values() function?

In my Vue3 component, I created a feature to showcase data using chips. The input is an Object with keys as indexes and values containing the element to be displayed. Here is the complete code documentation: <template> <div class="row" ...

Asserting types for promises with more than one possible return value

Struggling with type assertions when dealing with multiple promise return types? Check out this simplified code snippet: interface SimpleResponseType { key1: string }; interface SimpleResponseType2 { property1: string property2: number }; inter ...

ESLint detecting error with returning values in async arrow functions

Currently facing a minor inconvenience instead of a major problem. Here is the code snippet causing the issue: export const getLoginSession = async (req: NextApiRequest): Promise<undefined | User> => { const token = getTokenCookie(req) if (!t ...

Tips for utilizing the Axios API client created using the OpenAPITools code generator

Currently, I am utilizing the Swagger/OpenAPI Codegen tool to automatically generate an API client for the Fetch client within my Vue application. However, I have decided that I would prefer to make use of Axios instead. To begin this transition, I initiat ...