Reputation: 133
Can someone tell me why in the following code snippet the value of ColumnNames
is changed at the position of the debugger? It takes the same value as tempColumns
after tempColumns[k] = modi[i].data[k];
.
var addRecords= [];
var columns = ["Column1","Column2","Column4","Column5"]
var columnNames = {};
var modi = [{
data: {
Column1: 'bla'
}
},{
data:{
Column2: 'test'
}
}];
var tempColumns = {};
for( var n in columns){
var column = columns[n];
columnNames[column] = "";
}
for(var i in modi){
tempColumns = columnNames;
for(var k in modi[i].data){
tempColumns[k] = modi[i].data[k];
debugger;
}
addRecords.push(tempColumns);
}
Upvotes: 0
Views: 95
Reputation: 133
You need to make a copy of the object. When you say tempColumns = columnNames
then they both point to the same memory. with the following method you can make a copy from an object: JSON.parse(JSON.stringify(obj))
obj = {1:"hi", 2:"by"};
newobj = JSON.parse(JSON.stringify(obj));
newobj["1"] = "hello";
console.log(obj);
console.log(newobj);
Upvotes: 1
Reputation: 768
It is happening because you assigned columnNames to tempColumns before your debugger. In javascript values of objects are passed by reference which means that after line:
tempColumns = columnNames
tempColumns and columnNames point to the same position in memory.
Upvotes: 4