1

So my problem is simply, but i can't fix it. I have 2 objects one is temporary and second one is permanent, the temporary object taking data from permanent, but when i do actions on temporary, the permanent object chaing too example:

var permObject = {
    data1: 1,
    data2: 4,   
}
tmpObject = permObject
tmpObject.data2 -= tmpObject.data1;
console.log(tmpObject.data2); //data2 = 3
console.log(permObject.data2); //data2 = 3

So my question is, how can i take data from permanent object to temporary object, but when i do actions on temporary object then permanent object will not change?

Szarik
  • 17
  • 2
  • 8
  • 2
    Refer to this question: http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object – Sazid Apr 06 '14 at 09:44
  • You can check the below url for specific answer: https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object – pradeepks Oct 18 '18 at 07:18

3 Answers3

2

the following statement copy only the reference to your permanent object:

tmpObject = permObject

You need a clone of permananet object, like this:

function clone(obj) {
  if (null == obj || "object" != typeof obj) return obj;

  var copy = obj.constructor();
  for (var attr in obj) {
    if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  }

  return copy;
}


var permObject = {
data1: 1,
data2: 4,   
}
var tmpObject = clone(permObject);
tmpObject.data2 -= tmpObject.data1;
console.log(tmpObject.data2); //data2 = 3
console.log(permObject.data2); //data2 = 3

So reference

Community
  • 1
  • 1
ale
  • 10,012
  • 5
  • 40
  • 49
2

The thing you are doing on the 4th row:

tmpObject = permObject;

is that you create another reference to the same object, thus using the new reference, the old object gets changed. To fix it try cloning the old object: What is the most efficient way to deep clone an object in JavaScript?

Community
  • 1
  • 1
Kokozaurus
  • 639
  • 7
  • 22
0

Dr.Nefario's link is about deep clones, but in your case it doesn't matter whether the clone is shallow or deep since the object is shallow anyway. Shallow clones are easier.

If you're using the underscore library you could just use defaults:

tmpObject = _.defaults({}, permObject);
David Knipe
  • 3,417
  • 1
  • 19
  • 19