K
K
Konstantin2020-12-16 12:20:13
JavaScript
Konstantin, 2020-12-16 12:20:13

How to clone an array with an object?

There is a function that accepts an array of objects:

setDefault(defaultFilters: Filter[]) {
        this.defaultFilters = defaultFilters;
}


Where, Filter is a class:

export class Filter implements FilterModel {}

How to clone the defaultFilters object ?

Tried like this: this.defaultFilters = {...defaultFilters};

But it doesn't work for class objects.

Full code:

export abstract class FiltersRepository {
    public _filters: Filter[] = [];
    private filtersResponse: Filter[] = [];
    public filters$ = new Subject<Filter[]>();
    private filterUrlBuilder = new FilterUrlBuilder();
    private changes$ = new BehaviorSubject<string>(null);
    private default: Filter[];

    abstract init();

    setDefault(defaultFilters: Filter[]) {
        this.default = defaultFilters.slice();
        this._filters = defaultFilters;
    }

      modifyDefault() {
        this._filters.forEach((_filter) => {
            this.filtersResponse.forEach((responseFilter) => {
                if (_filter.title === responseFilter.title) {
                    if (Array.isArray(responseFilter.collection) && responseFilter.collection.length) {
                        _filter.collection = responseFilter.collection;
                    }
                }
            });
        });
    }
        reset() {
        console.log(this.default);
        this._filters = this.default;
        this.filter();
    }

}


First of all, I call the setDefault method and pass in the default filters. Next, I call modifyDefault which modifies the default filter with values ​​from the database.

Therefore, I am trying to make a clone of the default filters in order to be able to restore them in the reset () method

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2020-12-16
@Junart1

How to clone the defaultFilters object?

defaultFilters is an array.
If the question is "how to clone an array": defaultFilters.slice();
If the question is "how to clone an array and its contents": where is a method that creates a new instance of this class, copying the parameters. Because just copying public fields is absolutely not enough. defaultFilters.map(instance => instance.clone());clone

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question