I am trying to filter an array by string, but when I do it modifies the original array. My code is like this:
private copy: MenuItem[];
@Input() links: MenuItem[];
ngOnInit(): void {
this.copy = this.links;
}
public filter(target: MenuItem): void {
console.log(target);
let link = this.links.find((link: MenuItem) => link.path === target.path);
if (!link) return;
console.log(link);
this.copy.forEach((item: MenuItem) => {
if (item.path !== link.path) return;
let children = [...item.children];
link.childrenCount = children.length;
console.log(children.length);
console.log(item.children.length);
link.children = children.filter((child: MenuItem) => child.label.indexOf(item.filterChildren) > -1);
});
}
As you can see, I try to clone the children of the copied array, but when I try to filter, both item.children and children are modified. I don't want the items in the copy array to ever change, just the one in links.
I have tried a few ways. The way I thought would work was this:
public filter(target: MenuItem): void {
let link = this.links.find((link: MenuItem) => link.path === target.path);
if (!link) return;
this.copy.forEach((item: MenuItem) => {
if (item.path !== link.path) return;
link.childrenCount = item.children.length;
link.children = [...item.children.map((o) => ({ ...o }))].filter(
(child: MenuItem) => child.label.indexOf(item.filterChildren) > -1,
);
console.log(item.children.length);
console.log(link.children.length);
});
}
But it doesn't. Both item.children.length and link.children.length return the length of the filtered array, not the original size.
Can anyone help?
PS: This is the MenuItem model:
export class MenuItem {
label: string;
path: string;
filterChildren?: string;
open?: boolean;
children?: MenuItem[];
childrenCount?: number;
}