I am having some trouble with scoping for a project I was working and was able to generalize the problem as follows.
I have a list of objects that I want to iterate through using a foreach loop and pass into a helper function. In the helper function I want to have a locally scoped version of the object to operate on with out modifying the original object.
I understand that functions in javascript pass objects by reference but it should possible to locally scope the reference.
Does anyone have any as to what I am doing wrong? Is there a way to do this without cloning the object. I'd prefer not to have to rebuild each object since the objects are quite big and performance is important.
var gloabalList = [{n:0},{n:0},{n:0}];
var output = [];
gloabalList.forEach((item,index)=>{
gloabalList[index].n = index;
//at this point the value n is the index
messUpItem(item);
//at this point n is 2 we want it to be the index
output.push(item.n);
});
//we want this to be (1,2,3) but it is returning (2,2,2)
alert(output);
function messUpItem(item){
var x = item;// this should copy object val but its grabbing a reference
x.n = 2;
return item;
}