0

I'm using typescript (angular2) to create a "reset" method on an object array:

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

User can modify this objects, and he can also "reset" to default values. So I keep an array of objects called originalCars. So if he selects the first object and choose "reset", I want to do something like: car = originalCar.

I was doing this:

this.selectedCars().map(car=> {
  const originalCar = this.getOriginalCar(car.id);
  car.color = originalCar.color;
  car.brand = originalCar.brand;
  // ... I'm doing this to all properties of my object
 });

This is working, but I want to do it simple. Something like car = originalCar. I tried:

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

The selectedCars method is:

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

But It did not work. How can I do this?

1 Answer 1

2

With the map function you create a new array of whatever thing you return from the method. Which means, you have to overwrite the selectedCars property:

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

A more weird way of doing it, is by using the forEach method. That would be something like this:

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

If you just want to reset one car by id:

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 come to light, and your selectedCars() is a method. In that case you can do the following:

this.selectedCars().forEach((car, index) => {
  Object.assign(car, this.getOriginalCar(car.id));
});
It however does not feel proper, because you are updating an object and causing side-effects. Better would be to just create a new array/object collection
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.