1

Angular 8 with Firebase: Array .map () .slice () Do not work. Hi. I have been trying to make a copy of an array using .map () and .slice () in Angular 8, but using these methods I find that the copied array still has the reference to the original array.

I don't know if I'm doing it wrong, or these methods don't work in Angular 8.

 // Iniciamos la escucha de los cambios de la data del usuario
    if (!this.$userData) {
      this.$userData = this.userService.user().valueChanges().subscribe(data => {
        if (data) {
          this.userData = Object.assign({}, data);
          const temp = data.operationsList.map((x) => {
            x.bank = 'Popular';
            return x;
          });
          console.log(this.userData.operationsList, temp);
          if (!this.userData.validated) {
            this.router.navigate(['register/pendingValidation']);
          }
        }
      });
    }

console.log:

(2) [{…}, {…}]
0: {bank: "Popular", commission: 0, country: "ve", countryAllowed: "all", maximum: 0, …}
1: {bank: "Popular", commission: 0, country: "ve", countryAllowed: "all", maximum: 0, …}

(2) [{…}, {…}]
0: {bank: "Popular", commission: 0, country: "ve", countryAllowed: "all", maximum: 0, …}
1: {bank: "Popular", commission: 0, country: "ve", countryAllowed: "all", maximum: 0, …}

When modifying the copied array, the changes are also reflected in the original array.

2 Answers2

2

By copying an array, you're still keeping references to the same objects. So you need to go one level deeper:

const temp = data.operationsList.map((x) => Object.assign({}, x, { bank: 'Popular' }));
mbojko
  • 13,503
  • 1
  • 16
  • 26
  • Thanks, it worked for me. What I don't understand is why in javascritp the .map () function works fine, but using angular and firebase the reference to the original array is maintained. – Leandro Cardenas Sep 04 '19 at 21:19
  • Angular has nothing to do with it. If you `map` or `slice` an array of primitives (like numbers, strings or Booleans), you're fine, you're creating a legit, independent copy. With an array of objects you need to be a little more careful. – mbojko Sep 04 '19 at 21:31
  • Wr8. Still, if you want to assign value to array, then try using Spread Operator – Deepak swain Dec 09 '19 at 14:04
0

You're modifying a direct reference to the underlying data directly within your map. Change it to something like:

let tempX = Object.assign({}, x);
tempX.bank = 'Popular';
return tempX;
Jbluehdorn
  • 475
  • 2
  • 11