Sunstrike527
Sunstrike527

Reputation: 607

Why making changes to copy of array , affects to original array?

Im filtering menu array by permission once user logged in.
Im generating static menu and then give copy of array to filter.

constructor(public menu: MenuService, public permissionService: PermissionService) {
    console.log(menu.getMenu()) // this changes after filtering below
    this.menuItems = this.permissionService.filterMenuByTopic([...menu.getMenu()]); // here I'm using a copy
  }

Why do this happen ? If I have used spread operator and I do not use original array [...menu.getMenu()].
Only If I refresh the pages menu.getMenu() returns to original value

UPD 1
answering to the comments , here is getMenu() func

import { Injectable } from '@angular/core';
@Injectable()
export class MenuService {

  menuItems: Array<any>;

  constructor() {
    this.menuItems = [];
  }


  addMenu(items: Array<{
    text: string,
    heading?: boolean,
    link?: string,     // internal route links
    elink?: string,    // used only for external links
    target?: string,   // anchor target="_blank|_self|_parent|_top|framename"
    icon?: string,
    alert?: string,
    submenu?: Array<any>
  }>) {
    items.forEach((item) => {
      this.menuItems.push(item);
    });
  }


  getMenu() {
    return this.menuItems;
  }

}

Upvotes: 3

Views: 1193

Answers (2)

Sunstrike527
Sunstrike527

Reputation: 607

Thanks to Ivan's comment
I've made a deep clone by following

const cloned = menu.getMenu().map(x => Object.assign({}, x));
    console.log('cloned ', cloned)
    this.menuItems = this.permissionService.filterMenuByTopic(cloned);

One of the answer I have found here link

Upvotes: 0

IvanD
IvanD

Reputation: 2923

The spread operator creates a shallow copy. If the content of a menu was objects, then changing those objects in a copy array will change those objects in the original array (or technically, those two references are for the same object):

const obj1 = {
  val: 1
}

const obj2 = {
  val: 2
}

const obj3 = {
  val: 3
}

const arr = [obj1, obj2, obj3]

// creating a copy with the spread operator
const copy = [...arr]

// changing the second element in the copy
copy[1].val = 22

// the element in the original array is changed too
console.log(arr)

Upvotes: 2

Related Questions