Utilize array mapping to alter the complete object

In my project using TypeScript (Angular 2), I am working on creating a "reset" method for an object array:

cars [
  {
    id: 1,
    color: white,
    brand: Ford,
    model: Mustang,
    ...
  }, 
  ... 
]

Users have the ability to modify these objects, as well as reset them to their default values. To achieve this, I have created an array of objects called originalCars. When a user selects and chooses to "reset" the first object, I aim to execute something like: car = originalCar.

Initially, I attempted the following approach:

this.selectedCars().map(car=> {
  const originalCar = this.getOriginalCar(car.id);
  car.color = originalCar.color;
  car.brand = originalCar.brand;
  //... repeating this procedure for all properties of the object
 });

While this method is functional, I desire a simpler solution. Something along the lines of car = originalCar. My attempt was as follows:

this.selectedCars().map(car=> {
  const originalCar = this.getOriginalCar(car.id);
  return originalCar;
  // also tried car = originalCar;
 });

The selectedCars method looks like this:

selectedCars = () => {
    return this.cars.filter(car=> {
        return car.selected;
    });
};

Unfortunately, my attempts did not produce the desired outcome. Any suggestions on how I can simplify this process?

Answer №1

Utilizing the map function enables you to generate a new array based on the returned values from the method. This requires overwriting the selectedCars property:

this.selectedCars = this.selectedCars.map(car => this.getOriginalCar(car.id));

An alternative approach involves using the forEach method. The code would look something like this:

this.selectedCars.forEach((car, index) => {
  this.selectedCars[index] = this.getOriginalCar(car.id);
});

If resetting just one car by its id is your goal:

resetCar(id: number): void {
  const idx = this.selectedCars.findIndex((car) => car.id === id);

  if (idx > -1) {
    this.selectedCars[idx] = this.getOriginalCar(id);
  }
}

New information has surfaced indicating that your selectedCars() is actually a method. In such a scenario, you can implement the following solution:

this.selectedCars().forEach((car, index) => {
  Object.assign(car, this.getOriginalCar(car.id));
});
However, this might not be the most appropriate approach as it involves updating an object and causing side effects. It may be better to create a new array or object collection instead.

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

What is the best approach for managing optional object input parameters while also verifying the presence and accuracy of that specific property?

What is the best approach to handling a situation where a method has optional object member properties for the options object, but you still want to ensure the presence of that property with a default value in the resulting instance? Is creating a separate ...

What is the best way to change between different Angular 2 material tabs using typescript?

I need help with switching tabs using buttons <md-tab-group> <md-tab label="Tab 1">Content 1</md-tab> <md-tab label="Tab 2">Content 2</md-tab> </md-tab-group> <button md-button (click)="showTab1()">Show Tab 1< ...

The Angular checked functionality is not working as expected due to the presence of ngModel

Just getting started with Angular here. I’m working on a checkbox table that compares to another table and automatically checks if it exists. The functionality is all good, but as soon as I add ngModel to save the changes, the initial check seems to be ...

Parent observable method encountering an error while grouping multiple HTTP calls in Angular

I am facing an issue with managing multiple http calls and handling errors that may occur during their execution. I want to be able to identify which calls have failed so that I can retry them using a different method. However, without visibility at the co ...

Comparing ngrx and redux for managing state in stateless components

Exploring ngrx/angular 8 for the first time, I'm curious to know if the angular approach of using an observable to bind a state value to the this context still allows a component to remain presentational and stateless. In the realm of angular/ngrx, c ...

Creating an observer for a multiple selection dropdown in Aurelia: step by step tutorial

In my current setup, I have a dropdown menu that allows users to select a single option. This selection automatically provides me with the filtering value as an observable. Here is how it works: public months: any=[]; @observable public selectedMonth: ...

Manage sequential observables and await user input

I have a collection of items that I need to loop through in order to determine whether or not a modal dialog should be displayed to the user, and then pause the iteration until the user provides input. The items are stored within an observable as Observabl ...

The Npm audit inspection revealed a single low-risk vulnerability within the karma > expand-braces > braces component

The Npm audit report has flagged 'found 1 low severity vulnerability'. Manual review is needed for this vulnerability. Low Regular Expression Denial of Service Package braces Patched in >=2.3.1 Dependency of ...

What is the best way to retrieve a value from an object using a promise after a certain period of time

During an event, I receive a user object. When I try to access the user._properties.uid value before using setTimeout, it returns as undefined. However, when I implement setTimeout, the value is successfully fetched after a few seconds. Is there a way to ...

What method can be used to start an Angular app without the need for recompilation?

When I first created my Angular app, I used the command ng serve to build and run it. This command produced the following output: 10% building 3/3 modules 0 activei 「wds」: Project is running at http://localhost:4200/webpack-dev-server/ i 「wds」: we ...

Creating a custom URL in a React TypeScript project using Class components

I have been researching stack overflow topics, but they all seem to use function components. I am curious about how to create a custom URL in TypeScript with Class Components, for example http://localhost:3000/user/:userUid. I attempted the following: The ...

Guide on transforming an array containing indexed objects into a simple object

Can anyone help me with converting an array of this specific type? place: [ { "_id": "xxxxx", "loc": [ 0: "xxx", 1: "xxx" ] } ] Into something ...

Unable to access property value following AJAX call

Here is my code snippet: constructor(props: any) { super(props); this.state = { list: [], }; } public componentWillMount() { this.loadData(); } public loadData = () => { axios.get(someURL) .then((response) = ...

Using ngIf with a variable still incorporates HTML code

I have created the following Angular component: export class HeaderMainComponent { @Input() showFullMenu: boolean = false; } In my HTML file, I have included: <p>{{showFullMenu}}</p> <nav *ngIf="showFullMenu"> <li>Link 1< ...

Add a module to the main module or main component within the project

I have integrated a third-party library to manage the layout of my Angular application. I am considering importing it either in app.module.ts (the root module) or in app.component.ts (the root component). Do you think there would be any significant diff ...

Guide on setting up an AWS code pipeline for Elastic Beanstalk deployment on ASP.NET Core 5.0 with Angular

I am facing a challenge with deploying my ASP.NET Core 5.0 application with Angular to the EBS Windows environment using AWS CodePipeline (CI / CD). Despite searching various internet resources for solutions, I have not been able to find much help. My att ...

Having trouble retrieving files from an Angular2 service

I am facing an issue in creating an Angular2 service for downloading files from the server. I have a table where each record represents a single file. When clicking on a specific record, the download method is called: download(r: FileObject) { this.re ...

Although NgRx retrieves data from the API, it does not save it to the state

I've been struggling to grasp a fundamental concept in implementing ngrx. For instance, I have a situation where I need data from an API to validate information in my component, but once the validation is complete, I no longer need that data stored in ...

Determine the sum of exported identifiers based on ESLint rules

Currently, I am facing a requirement in my JavaScript/TypeScript monorepo to ensure that each library maintains a minimal amount of exported identifiers. Is there any existing eslint rule or package available that can keep track of the total number of exp ...

Is my unit testing for the angular material data table with an expansion panel running properly and detecting the completion of animation?

I am facing an issue with testing a large reusable component that wraps the material data table. The challenge lies in verifying the logic responsible for setting the initial state (open/closed) of each expansion row. I suspect that either the click event ...