I'm getting some unexpected behaviours (according to my concept) while executing some Array.prototype
functions (such as .map
, .reduce
, etc). The problem is that this functions are changing the values of the model variables. I created a piece of code to reproduce that:
import { Component, OnInit } from '@angular/core';
const getServerData = [
{ key: 'test1', value: 1 },
{ key: 'test2', value: 2 },
{ key: 'test3', value: 3 },
{ key: 'test4', value: 4 },
];
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
// docs receive values of const getServerData
docs = getServerData;
ngOnInit() {
const test = this.mapFunctionTest(this.docs);
console.log(this.docs);
}
// Here is the problem. I don't know why mapFunctionTest modifies the values
// of docs (value = 1000). What I expect is that the constant test should
// receive the returned array from mapFunctionTest and the value of docs
// keep unalterated (and wasn't assigned to value = 1000)
mapFunctionTest(array: any[]): any[] {
const testedArray = array.map((element) => {
element.value = 1000;
return element;
});
return testedArray;
}
}
What I intend with this code is that the constant "test" receives the array returned from the function mapFunctionTest
with the values:
[
{key: "test1", value: 1000},
{key: "test2", value: 1000},
{key: "test3", value: 1000},
{key: "test4", value: 1000}
]
while the docs variable stays with its content unchanged (which is not happening):
[
{key: "test1", value: 1},
{key: "test2", value: 2},
{key: "test3", value: 3},
{key: "test4", value: 4}
]
How to use Array.prototype
functions without change the value of its original array?