0

I have a problem with an array:
When I try to edit "brands.count", in countBrends() function, I get the error "count is read only".
Do you have any suggestions?
code:

allCars:Car[] 
brands:BrandCB[]
types:TypeCB[]
arr:any[] = [{count:1},{count:2},{count:3}]

constructor( private store:Store<StoreState>){ }

ngOnInit(): void {
    this.store.dispatch(carsActions.getAllCars())
    this.store.dispatch(brandsActions.getBrands())

    this.store.pipe(select(carsSelectors.getAllCars)).subscribe(
        cars => {
            this.allCars = [...cars]
        }
    )
    this.store.pipe(select(brandsSelectors.getBrands)).subscribe(
        brands => {
            this.brands = this.countBrands([...brands])
        }
    )

}

// it counts how many cars there are of the same brand 
// and enters the number in the "count" property of brands
countBrands(brands):BrandCB[]{
    return brands.forEach( brand =>{
        let count = 0
        this.allCars.forEach( car => {
            car.brand == brand.name ? count++ : null
        })
        brand.count = count
    })
}
CaneRandagio
  • 366
  • 2
  • 15
  • You will get a good answer in this thread. https://stackoverflow.com/questions/12482961/is-it-possible-to-change-values-of-the-array-when-doing-foreach-in-javascript – argoo Sep 02 '20 at 14:39
  • I tried to use the solutions you linked to me but they were not successful, there is always the same error – CaneRandagio Sep 02 '20 at 14:55

1 Answers1

1

You should avoid mutations where it's possible anyway. In this case I think you should dispatch new value of brand with increased count, because all states are immutable and you can't just assign new value in component.

SillyCoon
  • 89
  • 6
  • thanks! that's true, state is immutable but I use spread operator in assignment – CaneRandagio Sep 02 '20 at 15:11
  • it doesn't matter because it seems that all properties in state are frozen by Object.freeze or something like that and spreading doesn't create new object but references to existing. You should create copy of it by yourself. You can watch some example of it here tiny.cc/o3crsz – SillyCoon Sep 02 '20 at 16:18
  • I tried to convert in json and reconvert in js array object, it works but there is other problems. I choose to get the array from the store already with count number – CaneRandagio Sep 02 '20 at 17:10