Search code examples
angularangular-pipe

Angular pipe changes original object


I have a pipe to filter an Array by a daterange from userinput, the filter is working fine when making the array smaller but on increasing the daterange afterwards, the pipe is working with the small array again which was the result of the filter before.

Can anyone explain me what I am doing wrong? Thanks in advance.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'dateinrangePipe'
})

export class DateInRangePipe implements PipeTransform {
    transform(obj: any[], from: Date, to: Date): any[] {
        if (obj && from && to) {
            console.log('before:');
            obj.forEach(data => {
                console.log(data.name);
                data.series = data.series.filter((item: any) => {
                    return this.inRange(item.name, from, to);
                });
            });
        }
        console.log(obj);
        return [...obj];
    }

    inRange(date: Date, from: Date, to: Date): boolean {
        return date.getTime() >= from.getTime() &&
            date.getTime() <= to.getTime() ? true : false;
    }
}

Edit:

Pipe is used for the data of a ngx-chart

 <ngx-charts-line-chart
        ...
        [results]="multi | dateinrangePipe: from: to"
        ...>
 </ngx-charts-line-chart>

Solution

  • You return a copy of the input data, but this is pointless, as you assign a value to data.series before. As data is a reference, you modify obj.