简体   繁体   中英

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;
  }

}

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM