when changing value of copied variable it is also changing main variable value in angularjs

when changing value of copied variable it is also changing main variable value in angularjs

I am in a strange condition. I have an array of objects, I used angular.forEach to modify each object price key value but when I am changing it in each it is also changing main array object as well.
Have a look on code, you will understand then what I am trying to say.
var option_1_val = $scope.options.option_1_val;
        var option_2_val = $scope.options.option_2_val;

        var new_arr = [];
        var each ;
        each = sc.genies;
            var ob = {};
            ob = val;

            var priceA = angular.fromJson(ob.price);

            var option = option_1_val.replace(" ","-")+","+option_2_val.replace(" ","-");

            ob.price = priceA[option];


option = 'Non-Vegetarian,' (after calculating)

sc.genies = [{"gs_id":"3","user_id":"25","service_id":"7","price":"{\"Vegetarian,Bengali\":\"200\",\"Vegetarian
:"80","max_price":"4100","username":"abdul quadir","email":"abdul.quadir@kiozen.com","rating":"3"}]

now when I am repeating sc.genie, I have taken it in a new variable already "each" and then I am changing "price" key of each array to undefined but strange point is when I see in console value of price in sc.genies is also changed to "undefined". Huh!
I hope you got my point, please help me why is that happening.


Answer 1:

You should use angular.copy then when change in each value not affect to original value. because of angular.copy assign old value in new variable without reference.


var each ;
each = angular.copy(sc.genies);

instead of

each = sc.genies;

Answer 2:

There is a simple answer. The reason why “both” values changes, is because it is actually the same object. The variable val from this line angular.forEach(each,function(val,key){ ... contains a pointer to an object. It is not another object. It is the same object, it is only accessed via different variable name.

If you really want the original and working copy to be different objects, then you need to manually create new instance with the same values.

You can create copy of an object like this (good for simple objects):

 var copy = JSON.parse(JSON.stringify(originalObject));

or as pointed in the comment above, you can use angular.copy(source, destination). See the documentation https://docs.angularjs.org/api/ng/function/angular.copy