0

I have the following code (building my own little object-based-api...)

operator = {};

operator.set_data = function (json) {
    this.data = json
};

operator.first_load_chart = function () {
    let ref_data = operator.data;
    ref_data['date'] = ref_data['date'].map(x => x ? new Date(x * 1000) : null);
};

The operator.first_load_chart is run after operator.data is first assigned and operator.data['date'] is first unix timestamps.

Yet when I run console.log(operator.data['date']) in console after operator.first_load_chart operator.data['date] has now changed to a Date object?

Why is this, and how can I prevent this mutation?

54ka
  • 3,501
  • 2
  • 9
  • 24
uncool
  • 2,613
  • 7
  • 26
  • 55
  • 1
    This doesn't answer your question directly, but one trick I use to find what's causing an unexpected mutation is to use `Object.freeze(operator)` after setting the objects data/value. After that, any attempt to mutate the object will throw an error at the offending line. – Hussein Duvigneau Oct 16 '20 at 11:59
  • [Duplicate](https://www.google.com/search?q=site%3Astackoverflow.com+js+object+copy+property+changes) of [Modifying a copy of a JavaScript object is causing the original object to change](https://stackoverflow.com/q/29050004/4642212). – Sebastian Simon Oct 16 '20 at 16:09

1 Answers1

1
let ref_data = operator.data
    ref_data['date'] = ref_data['date'].map(x => x ? new Date(x * 1000) : null)

Here the ref_data is getting a reference to the actual data in the operator. So when you modify the value using ref_data, you are in turn updating the actual data in operator itself. If this is not intended you should make a copy of the data object before modifying.

let ref_data = Object.assign({},operator.data);
 ref_data['date'] = ref_data['date'].map(x => x ? new Date(x * 1000) : null)

Be wary that this is not a deep copy, i.e. if you have nested object you will need to handle it separtely.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
gvmani
  • 1,580
  • 1
  • 12
  • 20