Search code examples
javascriptarraysobjectjavascript-objects

Object gets changed even if I do not make any operations with it


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

Solution

  • 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);