Unexpected mutation of object array

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?

Answer

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.